Skip to content
Advertisement

Java: ArrayList sorting using comparators (ArrayLists doesn’t store objects)

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!

Advertisement

Answer

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))));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement