Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find maximum and minimum double value in a list

I have the following list of double values:

items {9.0, 4.0, 16.0, -6.0, 5.0}

I want to find the maximum and minimum values and for that I did:

double max = items.stream().max(Comparator.comparing(String::valueOf)).get();
double min = items.stream().min(Comparator.comparing(String::valueOf)).get();

The result that I got is max=9.0 and min=-6.0. I was expecting the maximum to be 16.0. Later, I changed 16.0 to 92.0 and it worked; it gave me max=92.0

Do you know how to solve that?

like image 910
Adam Amin Avatar asked Aug 07 '18 13:08

Adam Amin


2 Answers

What about :

double max = items.stream().mapToDouble(Double::doubleValue).max().getAsDouble();//16.0
double min = items.stream().mapToDouble(Double::doubleValue).min().getAsDouble();//-6.0
like image 133
YCF_L Avatar answered Sep 24 '22 22:09

YCF_L


You don't want to compare using strings but by the natural order of your double elements, i.e. Comparator.naturalOrder() instead of Comparator.comparing(String::valueOf).

Comparing via strings will result in the characters being compared and since the character value of 9 (of "9.0") is greater than 1 (of "16.0") you get the result you see. Changing "16.0" to "92.0" will result in . to be compared with 2 (since the first character is equal) and thus "92xx" is greater than "9.xx".

like image 27
Thomas Avatar answered Sep 24 '22 22:09

Thomas