Sort an ArrayList of Strings that are numbers

后端 未结 6 1681
孤街浪徒
孤街浪徒 2021-01-18 02:05

What is the fastest way to sort an ArrayList (in descending/ascending manner) that contains numbers, eg: { \"12\", \"3.5\", \"188\", \"33.03

6条回答
  •  隐瞒了意图╮
    2021-01-18 02:19

    You need to implement your own comparator, and use it on your list. You have to use BigDecimal, because you can have problems with loss of precision. You can use double, if your numbers are quire small precision.

    class MyComparator implements Comparator {
    
        public int compare(String o1, String o2){
            return new BigDecimal(o1).compareTo(new BigDecimal(o2));
        }
    
    }
    ...
    Collections.sort(list, new MyComparator());
    

提交回复
热议问题