Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an ArrayList of Strings that are numbers

What is the fastest way to sort an ArrayList<String> (in descending/ascending manner) that contains numbers, eg: { "12", "3.5", "188", "33.03" } ? Does Collections have a built-in method for this? Currently I am copying the ArrayList's contents to ArrayList<Double> and then using Collections.Sort() method and then putting it back to the initial array. Is there a faster way?

like image 367
astralmaster Avatar asked Oct 13 '14 11:10

astralmaster


2 Answers

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<String> 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...

like image 181
tobias_k Avatar answered Oct 12 '22 01:10

tobias_k


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<String, String> {

    public int compare(String o1, String o2){
        return new BigDecimal(o1).compareTo(new BigDecimal(o2));
    }

}
...
Collections.sort(list, new MyComparator());
like image 26
Beri Avatar answered Oct 12 '22 02:10

Beri