0

I'm trying to sort an arraylist of strings made up of numbers and letters, an example of the list once sorted would be:

name 1
name 2
name 3
name 11
name 12
name 13

But when I use collections.sort() it sorts this way:

name 1
name 11
name 12
name 13
name 2
name 3

Any ideas what the type of sort I'm looking for would be called or how do it?

Peter
  • 5,071
  • 24
  • 79
  • 115

5 Answers5

7

Strings are ordered alphabetically by default. You need to implement your own Comparator<String> or use an object that implements Comparable (or use a Comparator with it) to solve this, especially since the Strings you are using are mixtures of words and integers.

zw324
  • 26,764
  • 16
  • 85
  • 118
1

Implement comprable, override compareTo, parse the intand the name out and then you can sort by both of them. Do you want to sort soley by number or by both

aaronman
  • 18,343
  • 7
  • 63
  • 78
1

This happens because it's sorting alphabetically, looking for one character at a time.

name 13
name 2

Here, "name " is the same part, moving forward, you have "1" and "2". 1 comes before 2. Remember 13 and 2 are just Strings here not numbers.

You can write your own comparator. To achieve what you are trying.

Suraj Bajaj
  • 6,630
  • 5
  • 34
  • 49
0

You can use HashMap<Integer,String> map and can sort it

Virus
  • 167
  • 1
  • 11
0

as advised by others, you can write your own Comparator as shown below

      Comparator<? super String> myComparator = new Comparator<String>() {

        public int compare(String name1, String name2) {
            int num1 = Integer.parseInt(name1.split(" ")[1]);
            int num2 = Integer.parseInt(name2.split(" ")[1]);
            // > : Increasing order 
            // < : Decreasing order
            if(num1 < num2)
                    return 1;
            else
                    return -1;
        }

      };
      Collections.sort(names, myComparator);

Output:

name 91
name 12
name 11
name 2

mtk
  • 13,221
  • 16
  • 72
  • 112