Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - convert primitive double array to collection

Tags:

java

I'm looking to have an array of floats(doubles) & integers as below -

double[] myArr = {0, 0, 95, 9.5, 19, 610.5, 1217, 5.14, 4038.66, 10.23, 7961, 828, 199858, 37325.3};

I then have this function that returns the max & min

    public static void getMaxArrVal(double[] myArr) {           

        myCol = /* Code to convert myarr to collection should come here */
        System.out.println(Collections.min(myCol ));
        System.out.println(Collections.max(myCol ));
    }
}

getMaxArrVal(myArr);

I'm having problems converting primitive data type to a collection.I tried converting this to double list, tried by converting myArr to char/String to check a few things but nothing has worked obviously.

I keep seeing the compilation error of primitive data type. I did try Double too but no luck.

How could I possibly convert the array to collection & calculate min/max on this one. I'd appreciate any help her please.

like image 883
usert4jju7 Avatar asked Dec 25 '22 08:12

usert4jju7


2 Answers

This works nicely with Java 8:

Arrays.stream(myArr).boxed().collect(Collectors.toCollection(ArrayList::new));

Any Collection may be used instead of ArrayList, of course. The code I have here may actually be simplified to Collectors.toList().

Also, as noted in @nukie's answer, DoubleStream has its own min() and max() methods, rendering the conversion useless. Merely use two streams created using Arrays.stream(myArr) and call these methods.

like image 76
bcsb1001 Avatar answered Jan 10 '23 08:01

bcsb1001


Guava comes with nice solution

Lists.newArrayList(double[])
like image 37
luk Avatar answered Jan 10 '23 08:01

luk