I have a list of strings which holds the double value. Since it holds the double value. i used Collection.min to find the minimum value in the list.
Unfortunately i get a wrong result.
What is the best way to find the smallest double value in the list of strings?
Below is the code snippet with different results.
String a = "5.0";
String b = "7.0";
String c = "11.0";
List<String> test = new ArrayList<String>();
test.add(a);
test.add(b);
test.add(c);
System.out.println(Collections.min(test)); // Result 11.0
test = new ArrayList<String>();
test.add(a);
test.add(b);
System.out.println(Collections.min(test)); // 5.0
Thanks in advance.
When you run Collections.min
on a list of String
s, you get the String
that comes first in lexicographical order. That's "11.0" in your example.
You'll have to convert your List
to a List<Double>
in order for Collections.min
to give the result you want. Alternately, use can use public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
and pass to it a Comparator<String>
that parses the String
s into double
s and compares the doubles.
Quote from java Doc of Collections.min :
Returns the minimum element of the given collection, according to the natural ordering of its elements.
So the result is normal, it the natural ordering of strings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.