Mouthful OfTech
Mouthful OfTech

Reputation: 43

Java: ArrayList<String> 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!

Upvotes: 1

Views: 1758

Answers (3)

Amos Kosgei
Amos Kosgei

Reputation: 947

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));

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

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))));

Upvotes: 3

tevemadar
tevemadar

Reputation: 13195

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));
    }
});

Upvotes: 1

Related Questions