简体   繁体   中英

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?

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

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());

Try following code:

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

Output :

3.5
12.0
33.03
188.0

我认为您当前的方法可能很好,我会避免使用自定义Comparator因为您最终会将相同的字符串多次转换为数值(每次排序算法要比较2个值)而不是像您一样现在。

You can use Collections.sort() on List<String> , String is Comparable , but that comparison won't give you the right result.

Also you can define your own Comparator , and pass it to Collections.sort() .

您可以尝试使用sortedset接口,它可以在输入数据时为您提供排序数据。更好地实现您自己的比较器,我相信这对我来说没什么用处。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM