7

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?

7
  • You could implement your own Comparator, not sure if faster though. Commented Oct 13, 2014 at 11:54
  • 5
    why do you want to insert numbers as string in an arraylist Commented Oct 13, 2014 at 11:54
  • @GeorgeThomas Long story short: maintaining somebody else's code. Commented Oct 13, 2014 at 11:55
  • 2
    @GeorgeThomas I agree, if it were me, I would make them all doubles Commented Oct 13, 2014 at 11:55
  • Check this answer [here][1]. It works for every type of variables. [1]: stackoverflow.com/a/12771571/4096270 Commented Oct 13, 2014 at 12:01

6 Answers 6

9

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Although it is less code to write, I use Java 7, and as I understood, List doesn't have sort() method in version 7, right? Any workarounds?
You have to solutions, just like in older Java versions. Either you create a comparator, like in above example, or you have to make all your collection objects implement Comparable, and then use Collections.sort() :) So no, List has no sort method:) Any why? Because it is an iterface, and sometimes list does not have to be indexed.
@Ben In Java 8, List has a sort method.
7

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

1 Comment

Best Java 1.7 solution! Except you can use Double.parseDouble() instead BigDecimal if you know the values are of limited precision.
4

I think your current approach is probably fine, I would avoid using a custom Comparator because you would end up converting the same string into a numeric value multiple times (each time the sorting algorithm wants to compare 2 values) rather than just once as you do now.

2 Comments

Doesn't the OPs method risk ending up with "0.0999999999123" in the list when the original element was "0.1"?
The point about multiple conversions is a good one; one solution may be to save the converted values to a map and then check that. Which solution is faster however is a totally different question...
4

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

7 Comments

Indeed, why? I'm trying it now
thats just the way the author did it, I didnt downvote though
Pretty much what I did, yes, but there might be a faster way.
You can use comparator but I think this is the faster way. And yes why downvotes?
Personally I wouldn't use Floats here due to the possible loss of accuracy (depending of course on the input values) but in principle this should be fine.
|
1

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

Comments

1

You can try sortedset interface which enables you the sorted data during the time of entering the data.Better implement your own comparator which will be little beneficial i believe.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.