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?

0

5 Answers 5

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.

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

Comments

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

Comments

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.

Comments

0

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

Comments

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

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.