Home > Java > javaTutorial > How to Sort One List Based on the Order of Another List in Java?

How to Sort One List Based on the Order of Another List in Java?

Barbara Streisand
Release: 2024-11-02 15:46:29
Original
955 people have browsed it

How to Sort One List Based on the Order of Another List in Java?

Sorting One List Based on Another in Java

In Java, it is possible to sort a list based on another list's order. This can be useful in situations where you have a specific sequence of items in one list (listB) and you want to rearrange a second list (listA) to match that order.

One way to achieve this is by using the Collections.sort() method with a customized Comparator as follows:

<code class="java">Collections.sort(listToSort, new Comparator<T>() {
    @Override
    public int compare(T o1, T o2) {
        return listWithOrder.indexOf(o1) - listWithOrder.indexOf(o2);
    }
});</code>
Copy after login

Here, listToSort represents your unsorted list, and listWithOrder contains the desired order. This Comparator sorts listToSort based on the order of the elements in listWithOrder.

For Java 8 and later, you can simplify the code using lambdas and the comparingInt() method:

<code class="java">listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));</code>
Copy after login

The above is the detailed content of How to Sort One List Based on the Order of Another List in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template