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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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");
      }

2 Comments

@user1706269: If this was helpful, don't forget to accept the answer(click arrow next to the votes).
Today I was allowed to accept answers for the first time so I've come back to reward you, thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.