0

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mark
  • 1,360
  • 3
  • 20
  • 37

2 Answers2

4

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

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");
      }
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73