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.
<code class="java">Collections.sort(listToSort, Comparator.comparing(item -> listWithOrder.indexOf(item)));</code>
<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!