简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM