1

I am using the following java code to sort the values: -

 Collections.sort(values);

It is working correctly except that it is sorting as follows: - 1 10 2 3 4

I need it to sort as follows: - 1 2 3 4 10

Mansoor Gee
  • 1,051
  • 8
  • 20
Wael
  • 1,453
  • 4
  • 20
  • 32

3 Answers3

4

You can pass a Comparator into the sort call to convert the string into a number during the sort, or store the value as a number in the first place. When comparing strings, 10 comes before 2.

Alternatively, define a compareTo in your class (and have the class it implement Comparable) if you always need to sort the same way, and skip the Comparator.

Dave Newton
  • 156,572
  • 25
  • 250
  • 300
1

You are sorting Strings. You can change values to store a subclass of Number or implement your own Comparator to pass as the segment argument of the sort method which will do a "natural sort."

See this question for more details: Natural sort order string comparison in Java - is one built in?

Community
  • 1
  • 1
Brigham
  • 14,045
  • 3
  • 36
  • 47
1

Use a List<Integer> (not a List<String> which it looks like you are using).

Bohemian
  • 389,931
  • 88
  • 552
  • 692