Reputation: 1456
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?
Upvotes: 14
Views: 18124
Reputation: 59950
What about :
double max = items.stream().mapToDouble(Double::doubleValue).max().getAsDouble();//16.0
double min = items.stream().mapToDouble(Double::doubleValue).min().getAsDouble();//-6.0
Upvotes: 12
Reputation: 45309
There's a more appropriate stream type for doubles. Using it, you can get min
and max
in one terminal operation (eliminating the need to supply a comparator in the process):
DoubleSummaryStatistics stats = items.stream().mapToDouble(d -> d)
.summaryStatistics();
//even better: DoubleStream.of(9.0, 4.0, 16.0, -6.0, 5.0).summaryStatistics()
And stats
will have:
count=5, sum=28.000000, min=-6.000000, average=5.600000, max=16.000000
Upvotes: 5
Reputation: 54148
Your are comparing them as String
so by alphabetical order : 1xx is before 9xx
You need to compare then as Double or Integer
, so use Comparator.comparing(Double::valueOf)
(or Integer::valueOf
)
Upvotes: 4
Reputation: 88707
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"
.
Upvotes: 12
Reputation: 533492
It appears you want to compare the number numerically instead of their String representation e.g. "16.0" < "9.0"
as '1' < '9'
List<Double> items = Arrays.asList(9.0, 4.0, 16.0, -6.0, 5.0);
double max = items.stream().max(Comparator.naturalOrder()).get();
double min = items.stream().min(Comparator.naturalOrder()).get();
System.out.println(min + " " + max);
prints
-6.0 16.0
Upvotes: 7