Reputation: 1400
I have an string arraylist with values like
2.25mm
2.75mm
5mm
5.5mm
When sorting the values that do not have decimal place sort incorrectly. 5.5mm proceeds 5mm where 2.25mm correctly proceeds 2.75mm
I have not had any experience with comparator so any help would be much appreciated.
Upvotes: 0
Views: 1592
Reputation: 34387
Since you are sorting your entries as String
, its not behaving as numeric sorting as in character notiation, .
(ASCII 46) comes before m
(ASCII 109) hence 5.5mm
is moved up than 5mm
.
Create another decimal point list by stripping the mm
, sort the new decimal list as below:
List<BigDecimal> decimalList = new ArrayList<BigDecimal>();
for(String elem: myList){
decimalList.add(new BigDecimal(elem.substring(0, elem.length()-2)));
}
Collections.sort(decimalList);
If you want, recreate your sorted string list back as:
myList.clear();
for(BigDecimal elem: decimalList){
myList.add(elem.doubleValue()+"mm");
}
Upvotes: 3
Reputation: 198471
You're sorting these as strings, and the character m
comes before the character .
.
It'd probably be easier just to remove the mm
and to sort parsed BigDecimal
values.
Upvotes: 4