Sort an ArrayList of Strings that are numbers

后端 未结 6 1683
孤街浪徒
孤街浪徒 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:44

    If you are using Java 8, you can use Comparator.comparing(Double::parseDouble) to quickly create a comparator using parseDouble. This should (see below) call the function just once for each entry, and not once for each pair.

    List list = Arrays.asList( "12", "3.5", "188", "33.03" );
    list.sort(Comparator.comparing(Double::parseDouble));
    System.out.println(list);
    

    Output:

    [3.5, 12, 33.03, 188]
    

    Update: Well, I thought this would call the comparator function just once for each element, like using a key-function in Python, but after a quick test using a function increasing a counter each time it is called, the function is called just as often as using an old-style "pair"-comparator. Still, a bit shorter...

提交回复
热议问题