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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 21:36:29710browse

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>

Improved Java 8 Solution

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

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!

Statement:
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