Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-01 21:36:29
Original
723 people have browsed it

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

Sorting One Java List Based on Another

When reordering elements in a list (listA), users may desire to retain the new order upon retrieval. Due to constraints, it may be necessary to sort listA after retrieval based on another list (listB) that defines the desired order.

To achieve this sorting, you can leverage Java's Collections.sort method with a custom comparator. The comparator function should compare elements based on their indices in listB.

Java 8 Solution

<code class="java">Collections.sort(listToSort, Comparator.comparing(item -> listWithOrder.indexOf(item)));</code>
Copy after login

Improved Java 8 Solution

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

This improved solution uses comparingInt instead of comparing, providing enhanced performance.

The above is the detailed content of How to Sort a Java List Based on the Order of Another List?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!