Sort ArrayList strings that are numbers

What is the fastest sorting method ArrayList<String>(descending / ascending) that contains numbers, for example { "12", "3.5", "188", "33.03" }:? Does it have a Collectionsbuilt-in method for this? I am currently copying the contents ArrayListto ArrayList<Double>, and then using the method Collections.Sort()and then returning it back to the original array. Is there a faster way?

+4
source share
6 answers

You need to implement your own comparator and use it on your list. You should use BigDecimal because you may have problems with accuracy loss. You can use double if your numbers have little 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());
+6
source

If you use Java 8, you can use Comparator.comparing(Double::parseDouble)to quickly create a comparator with parseDouble. This should (see below) call the function only once for each record, 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);

Conclusion:

[3.5, 12, 33.03, 188]

: , - , , key - Python, , , , , "" - . , ...

+8

:

String test[] = {"12", "3.5", "188", "33.03"};
double numbers[] = new double[test.length];
for (int i = 0; i < test.length; i++) {
     numbers[i] = Double.parseDouble(test[i]);
}
Arrays.sort(numbers);
for (double i : numbers) {
     System.out.println(i);
}

:

3.5
12.0
33.03
188.0
+4

, , , , Comparator, ( , 2 ), .

+4

You can use Collections.sort()on List<String>, String - Comparable, but this comparison will not give you the correct result.

You can also define your own Comparatorand pass it on Collections.sort().

+1
source

You can try the sortedset interface, which allows you to sort data during data entry. Implement your own comparator, which will be of little use, I suppose.

+1
source

All Articles