[Solved] What is the best way to sort an ArrayList based on a already sorted ArrayList?


Your solution is has O(n^2) time complexity – those nested loops will be very slow for large lists.

However, with the aid of a HashMap, an O(n) solution is possible.

Map<String, NameAndValue> map = new HashMap<>();
for (NameAndValue x : arrayB)
    map.put(x.getName(), x);

for (int i = 0; i < arrayA.size(); i++) 
    arrayB.set(i, map.get(arrayA.get(i).getName()));

This only works if the lists have the same fruit in different orders and no fruit appears twice.

solved What is the best way to sort an ArrayList based on a already sorted ArrayList?