Converting negative array values of different data types (string, double, int) into positive

187 views Asked by At

I have multiple arrays all with different data types (string, double, int) the data type stays the same for the array but each array has a different data type. Ex. Array1 has string values, Array 2 double values, Array 3 int values. All of which contain negative numbers and I want to convert those negative numbers all into positive and put them back into their respective arrays.

I initially thought of using Math.abs but i'd need to make a loop (i assume a for loop) in which I convert all data values to int and then apply Math.abs to those values. But I'm not sure how I can make the loop work for all the different data types as well as placing the new values back into the respective array's in correct order.

I also thought of using Parseint for the conversion but that only applies to strings going to int which doesn't help with the doubles or ints. I need the code to do it all in one universal loop.

1

There are 1 answers

0
lane.maxwell On

This isn't pretty, but it provides a single method that you can pass an array of Strings, Doubles, or Integers to and get back an array of their absolute values.

public <T> T[] abs(T[] objects) {
    if (objects != null) {
        if (objects instanceof Double[] doubles) {
            return (T[]) Arrays.stream(doubles).map(Math::abs).toArray(Double[]::new);
        } else if (objects instanceof Integer[] integers) {
            return (T[]) Arrays.stream(integers).map(Math::abs).toArray(Integer[]::new);
        } else if (objects instanceof String[] strings) {
            return (T[]) Arrays.stream(strings).map(Integer::parseInt).map(Math::abs).map(String::valueOf).toArray(String[]::new);
        }
    }

    return objects;
}

Using the method would look like this:

String [] negativeStrings = new String[] {"-1", "-2", "3", "-6"};
Double [] negativeDoubles = new Double[] {-1.0, -2.3, -4.2, 5.0};
Integer [] negativeIntegers = new Integer[] {-1, -2, 3, -6};

Double[] absDoubles = abs(negativeDoubles);
String[] absStrings = abs(negativeStrings);
Integer[] absIntegers = abs(negativeIntegers);

Or, simply:

Integer[] absIntegers = abs(new Integer[] {-1, -2, 3, -6});