1

I want to sort an ArrayList of type String using a comparator. I have only found examples on how to do it if an ArrayList stores objects.

I have an ArrayList of strings that have 10 symbols and last 5 of those symbols are digits that form a number. I want to solve an array list in ascending order of those numbers that are at the end of each string. How can I do that?

Thanks!

5
  • 3
    String is an Object. What have you tried (exactly)? Let's see some code. Commented Oct 28, 2017 at 16:31
  • private static ArrayList<String> allCodes = new ArrayList<String>(); //add some codes in .... private void sortAllCodesNumbers (){ Collections.sort(allCodes, allCodes.getCompByNum()); } Commented Oct 28, 2017 at 16:39
  • public static Comparator<String> getCompByNum() { Comparator comp = new Comparator<String>(){ @Override public int compare(allBooks b1, allBooks b2) { String IDnumbers1 = b1.substring(AUTHOR_ID_LENGHT+GENRE_LENGTH); int number1 = Integer.parseInt(IDnumbers1); String IDnumbers2 = b2.substring(AUTHOR_ID_LENGHT+GENRE_LENGTH); int number2 = Integer.parseInt(IDnumbers1); return number1.compareTo(number2); } }; return comp; } Commented Oct 28, 2017 at 16:42
  • Variant of stackoverflow.com/questions/16425127/… ? Commented Oct 28, 2017 at 16:43
  • check this:List<String> list= new ArrayList<String>(); list.add("abc456"); list.add("abc123"); list.add("abc012"); System.out.println(list); Collections.sort(list); System.out.println(list); output:[abc456, abc123, abc012] [abc012, abc123, abc456] Commented Oct 28, 2017 at 16:51

3 Answers 3

3

This is one way to accomplish your task; sorted accepts a Comparator object.

List<String> result = myArrayList.stream().sorted(Comparator.comparingInt(e -> Integer.parseInt(e.substring(5))))
                                          .collect(Collectors.toList());

or simply:

myArrayList.sort(Comparator.comparingInt(e -> Integer.parseInt(e.substring(5))));
Sign up to request clarification or add additional context in comments.

2 Comments

No need for a regexp. Why not just e.substring(5)?
@JBNizet true, I shall use your idea.
1

Collections.sort can sort you a list with a Comparator. Plus you need String.substring:

Collections.sort(list, new Comparator<String>(){
    @Override
    public int compare(String o1, String o2) {
        return o1.substring(5).compareTo(o2.substring(5));
    }
});

Comments

0
Collections.sort(list, String::compareTo);

The above code does the job.

If you want more control, you could use/chain with one of the static methods available in the Comparator Interface.

Collectios.sort(list, Comparator.comparing(String::CompareTo).thenComparingInt(String::length));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.