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

Posted on

Problem :

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.

Solution :

Using Java 8:

    Comparator.comparing(item -> listWithOrder.indexOf(item)));

or better:


Collections.sort(listB, new Comparator<Item>() {
    public int compare(Item left, Item right) {
        return, listA.indexOf(right));

This is quite inefficient, though, and you should probably create a Map<Item, Integer> from listA to lookup the positions of the items faster.

Guava has a ready-to-use comparator for doing that: Ordering.explicit()

Let’s say you have a listB list that defines the order in which you want to sort listA. This is just an example, but it demonstrates an order that is defined by a list, and not the natural order of the datatype:

List<String> listB = Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday");

Now, let’s say that listA needs to be sorted according to this ordering. It’s a List<Item>, and Item has a public String getWeekday() method.

Create a Map<String, Integer> that maps the values of everything in listB to something that can be sorted easily, such as the index, i.e. "Sunday" => 0, …, "Saturday" => 6. This will provide a quick and easy lookup.

Map<String, Integer> weekdayOrder = new HashMap<String, Integer>();
for (int i = 0; i < listB.size(); i++)
    String weekday = listB.get(i);
    weekdayOrder.put(weekday, i);

Then you can create your custom Comparator<Item> that uses the Map to create an order:

public class ItemWeekdayComparator implements Comparator<Item>
    private Map<String, Integer> sortOrder;

    public ItemWeekdayComparator(Map<String, Integer> sortOrder)
        this.sortOrder = sortOrder;

    public int compare(Item i1, Item i2)
        Integer weekdayPos1 = sortOrder.get(i1.getWeekday());
        if (weekdayPos1 == null)
            throw new IllegalArgumentException("Bad weekday encountered: " +
        Integer weekdayPos2 = sortOrder.get(i2.getWeekday());
        if (weekdayPos2 == null)
            throw new IllegalArgumentException("Bad weekday encountered: " +
        return weekdayPos1.compareTo(weekdayPos2);

Then you can sort listA using your custom Comparator.

Collections.sort(listA, new ItemWeekdayComparator(weekdayOrder));

Speed improvement on JB Nizet’s answer (from the suggestion he made himself). With this method:

  • Sorting a 1000 items list 100 times improves speed 10 times on my
    unit tests.

  • Sorting a 10000 items list 100 times improves speed 140 times (265 ms for the whole batch instead of 37 seconds) on my
    unit tests.

This method will also work when both lists are not identical:

 * Sorts list objectsToOrder based on the order of orderedObjects.
 * Make sure these objects have good equals() and hashCode() methods or
 * that they reference the same objects.
public static void sortList(List<?> objectsToOrder, List<?> orderedObjects) {

    HashMap<Object, Integer> indexMap = new HashMap<>();
    int index = 0;
    for (Object object : orderedObjects) {
        indexMap.put(object, index);

    Collections.sort(objectsToOrder, new Comparator<Object>() {

        public int compare(Object left, Object right) {

            Integer leftIndex = indexMap.get(left);
            Integer rightIndex = indexMap.get(right);
            if (leftIndex == null) {
                return -1;
            if (rightIndex == null) {
                return 1;

            return, rightIndex);

Problem : sorting a list of Pojo on the basis of one of the field’s all possible values present in another list.

Take a look at this solution, may be this is what you are trying to achieve:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {

  public static void main(String[] args) {
    List<Employee> listToSort = new ArrayList<>();
    listToSort.add(new Employee("a", "age11"));
    listToSort.add(new Employee("c", "age33"));
    listToSort.add(new Employee("b", "age22"));
    listToSort.add(new Employee("a", "age111"));
    listToSort.add(new Employee("c", "age3"));
    listToSort.add(new Employee("b", "age2"));
    listToSort.add(new Employee("a", "age1"));

    List<String> listWithOrder = new ArrayList<>();

    Collections.sort(listToSort, Comparator.comparing(item -> 


class Employee {
  String name;
  String age;

  public Employee(String name, String age) {
    super(); = name;
    this.age = age;

  public String getName() {
    return name;

  public String getAge() {
    return age;

  public String toString() {
    return "[name=" + name + ", age=" + age + "]";

[[name=a, age=age11], [name=a, age=age111], [name=a, age=age1], [name=b, age=age22], [name=b, age=age2], [name=c, age=age33], [name=c, age=age3]]

Here is a solution that increases the time complexity by 2n, but accomplishes what you want. It also doesn’t care if the List R you want to sort contains Comparable elements so long as the other List L you use to sort them by is uniformly Comparable.

public class HeavyPair<L extends Comparable<L>, R> implements Comparable<HeavyPair<L, ?>> {
    public final L left;
    public final R right;

    public HeavyPair(L left, R right) {
        this.left = left;
        this.right = right;

    public compareTo(HeavyPair<L, ?> o) {
        return this.left.compareTo(o.left);

    public static <L extends Comparable<L>, R> List<R> sort(List<L> weights, List<R> toSort) {
        assert(weights.size() == toSort.size());
        List<R> output = new ArrayList<>(toSort.size());
        List<HeavyPair<L, R>> workHorse = new ArrayList<>(toSort.size());
        for(int i = 0; i < toSort.size(); i++) {
            workHorse.add(new HeavyPair(weights.get(i), toSort.get(i)))
        for(int i = 0; i < workHorse.size(); i++) {
        return output;

Excuse any terrible practices I used while writing this code, though. I was in a rush.

Just call HeavyPair.sort(listB, listA);

Edit: Fixed this line return this.left.compareTo(o.left);. Now it actually works.

Here is an example of how to sort a list and then make the changes in another list according to the changes exactly made to first array list. This trick will never fails and ensures the mapping between the items in list. The size of both list must be same to use this trick.

    ArrayList<String> listA = new ArrayList<String>();
    ArrayList<String> listB = new ArrayList<String>();
    int j = 0;
    // list of returns of the compare method which will be used to manipulate
    // the another comparator according to the sorting of previous listA
    ArrayList<Integer> sortingMethodReturns = new ArrayList<Integer>();

    public void addItemstoLists() {
        listA.add("Value of Z");
        listA.add("Value of C");
        listA.add("Value of F");
        listA.add("Value of A");
        listA.add("Value of Y");

        listB.add("this is the value of Z");
        listB.add("this is the value off C");
        listB.add("this is the value off F");
        listB.add("this is the value off A");
        listB.add("this is the value off Y");

        Collections.sort(listA, new Comparator<String>() {

            public int compare(String lhs, String rhs) {
                // TODO Auto-generated method stub
                int returning = lhs.compareTo(rhs);
                return returning;

        // now sort the list B according to the changes made with the order of
        // items in listA
        Collections.sort(listB, new Comparator<String>() {

            public int compare(String lhs, String rhs) {
                // TODO Auto-generated method stub

                // comparator method will sort the second list also according to
                // the changes made with list a
                int returning = sortingMethodReturns.get(j);
                return returning;



import java.util.Comparator;
import java.util.List;

public class ListComparator implements Comparator<String> {

    private final List<String> orderedList;
    private boolean appendFirst;

    public ListComparator(List<String> orderedList, boolean appendFirst) {
        this.orderedList = orderedList;
        this.appendFirst = appendFirst;

    public int compare(String o1, String o2) {
        if (orderedList.contains(o1) && orderedList.contains(o2))
            return orderedList.indexOf(o1) - orderedList.indexOf(o2);
        else if (orderedList.contains(o1))
            return (appendFirst) ? 1 : -1;
        else if (orderedList.contains(o2))
            return (appendFirst) ? -1 : 1;
        return 0;

You can use this generic comparator to sort list based on the the other list.
For example, when appendFirst is false below will be the output.

Ordered list: [a, b]

Un-ordered List: [d, a, b, c, e]

[a, b, d, c, e]

One way of doing this is looping through listB and adding the items to a temporary list if listA contains them:

List<?> tempList = new ArrayList<?>();
for(Object o : listB) {
    if(listA.contains(o)) {
return tempList;

Not completely clear what you want, but if this is the situation:

And you want to load them both and then produce:

Then maybe this?

List c = new ArrayList(b.size());
for(int i=0;i<b.size();i++) {

that requires an extra copy, but I think to to it in place is a lot less efficient, and all kinds of not clear:

for(int i=0;i<b.size();i++){
    int from = b.get(i);
    if(from == i) continue;
    T tmp = a.get(i);

Note I didn’t test either, maybe got a sign flipped.

public static class SortedDependingList<E> extends AbstractList<E> implements List<E>{
    private final List<E> dependingList;
    private final List<Integer> indices;

    public SortedDependingList(List<E> dependingList) {
        this.dependingList = dependingList;
        indices = new ArrayList<>();

    public boolean add(E e) {
        int index = dependingList.indexOf(e);
        if (index != -1) {
            return addSorted(index);
        return false;

     * Adds to this list the element of the depending list at the given
     * original index.
     * @param index The index of the element to add.
    public boolean addByIndex(int index){
        if (index < 0 || index >= this.dependingList.size()) {
            throw new IllegalArgumentException();
        return addSorted(index);

     * Returns true if this list contains the element at the
     * index of the depending list.
    public boolean containsIndex(int index){
        int i = Collections.binarySearch(indices, index);
        return i >= 0;

    private boolean addSorted(int index){
        int insertIndex = Collections.binarySearch(indices, index);
        if (insertIndex < 0){
            insertIndex = -insertIndex-1;
            this.indices.add(insertIndex, index);
            return true;
        return false;

    public E get(int index) {
        return dependingList.get(indices.get(index));

    public int size() {
        return indices.size();

try this for java 8:

listB.sort((left, right) ->, list.indexOf(right)));


listB.sort(Comparator.comparingInt(item -> list.indexOf(item)));

If the two lists are guaranteed to contain the same elements, just in a different order, you can use List<T> listA = new ArrayList<>(listB) and this will be O(n) time complexity. Otherwise, I see a lot of answers here using Collections.sort(), however there is an alternative method which is guaranteed O(2n) runtime, which should theoretically be faster than sort‘s worst time complexity of O(nlog(n)), at the cost of 2n storage

Set<T> validItems = new HashSet<>(listB);
listB.forEach(item -> {
  if(validItems.contains(item)) {

List<String> listA;
Comparator<B> comparator = Comparator.comparing(e -> listA.indexOf(e.getValue()));
//call your comparator inside your list to be sorted

If the object references should be the same, you can initialize listA new.

listA = new ArrayList(listB)

Like Tim Herold wrote, if the object references should be the same, you can just copy listB to listA, either:

listA = new ArrayList(listB);

Or this if you don’t want to change the List that listA refers to:


If the references are not the same but there is some equivalence relationship between objects in listA and listB, you could sort listA using a custom Comparator that finds the object in listB and uses its index in listB as the sort key. The naive implementation that brute force searches listB would not be the best performance-wise, but would be functionally sufficient.

IMO, you need to persist something else. May be not the full listB, but something. May be just the indexes of the items that the user changed.

Try this. The code below is general purpose for a scenario where listA is a list of Objects since you did not indicate a particular type.

Object[] orderedArray = new Object[listA.size()];

for(int index = 0; index < listB.size(); index ++){
    int position = listB.get(index); //this may have to be cast as an int
    orderedArray[position] = listA.get(index);
//if you receive UnsupportedOperationException when running listA.clear()
//you should replace the line with listA = new List<Object>() 
//using your actual implementation of the List interface

Just encountered the same problem.
I have a list of ordered keys, and I need to order the objects in a list according to the order of the keys.
My lists are long enough to make the solutions with time complexity of N^2 unusable.
My solution:

<K, T> List<T> sortByOrder(List<K> orderedKeys, List<T> objectsToOrder, Function<T, K> keyExtractor) {
    AtomicInteger ind = new AtomicInteger(0);
    Map<K, Integer> keyToIndex = -> k, k -> ind.getAndIncrement(), (oldK, newK) -> oldK));
    SortedMap<Integer, T> indexToObj = new TreeMap<>();
    objectsToOrder.forEach(obj -> indexToObj.put(keyToIndex.get(keyExtractor.apply(obj)), obj));
    return new ArrayList<>(indexToObj.values());

The time complexity is O(N * Log(N)).
The solution assumes that all the objects in the list to sort have distinct keys. If not then just replace SortedMap<Integer, T> indexToObj by SortedMap<Integer, List<T>> indexToObjList.

To avoid having a very inefficient look up, you should index the items in listB and then sort listA based on it.

Map<Item, Integer> index = IntStream.range(0, listB.size()).boxed()
  .collect(Collectors.toMap(listB::get, x -> x));

listA.sort((e1, e2) ->, index.get(c2));

So for me the requirement was to sort originalList with orderedList. originalList always contains all element from orderedList, but not vice versa. No new elements.

fun <T> List<T>.sort(orderedList: List<T>): List<T> {
    return if (size == orderedList.size) {
    } else {
        var keepIndexCount = 0
        mapIndexed { index, item ->
            if (orderedList.contains(item)) {
                orderedList[index - keepIndexCount]
            } else {

P.S. my case was that I have list that user can sort by drag and drop, but some items might be filtered out, so we preserve hidden items position.

If you want to do it manually. Solution based on bubble sort (same length required):

public void sortAbasedOnB(String[] listA, double[] listB) {
    for (int i = 0; i < listB.length - 1; i++) {
        for (int j = listB.length - 1; j > i; j--) {
            if (listB[j] < listB[j - 1]){
                double tempD = listB[j - 1];
                listB[j - 1] = listB[j];
                listB[j] = tempD;
                String tempS = listA[j - 1];
                listA[j - 1] = listA[j];
                listA[j] = tempS;

In Java there are set of classes which can be useful to sort lists or arrays. Most of the following examples will use lists but the same concept can be applied for arrays. A example will show this.

We can use this by creating a list of Integers and sort these using the Collections.sort(). The Collections (Java Doc) class (part of the Java Collection Framework) provides a list of static methods which we can use when working with collections such as list, set and the like. So in a nutshell, we can sort a list by simply calling: java.util.Collections.sort(the list) as shown in the following example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class example {
  public static void main(String[] args) {
    List<Integer> ints = new ArrayList<Integer>();

The above class creates a list of four integers and, using the collection sort method, sorts this list (in one line of code) without us having to worry about the sorting algorithm.

Leave a Reply

Your email address will not be published. Required fields are marked *