Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java how do you sort one list based on another?

I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.

My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.

So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.

like image 554
Debacle Avatar asked Aug 08 '13 15:08

Debacle


People also ask

How do you sort a list of objects based on an attribute of the objects in Java?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

Can we sort list of list in Java?

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

How do you sort a double list?

You can use sort(List<T> list) method. It will sort the double list in ascending order. If you want to sort it in descending order, you can use sort(List<T> list, Comparator<? super T> c) .


1 Answers

Using Java 8:

Collections.sort(listToSort,      Comparator.comparing(item -> listWithOrder.indexOf(item))); 

or better:

listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf)); 
like image 52
Thermech Avatar answered Nov 05 '22 19:11

Thermech