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,071
  • 8
  • 20
Wael
  • 1,533
  • 4
  • 20
  • 35

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
  • 158,873
  • 26
  • 254
  • 302
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,395
  • 3
  • 38
  • 48
1

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722