Sort object List by another List using Java Comparators
As I see it, you need to sort elements by age if the name is contained in the inputB
list and leave the rest of the elements as they are if they aren't contained in the inputB
list. The elements sorted by age should appear at the top of the result, while the unsorted ones should appear at the bottom.
If this is what you need to do, you can use Comparator.comparingInt
and let it return an integer that is either the age (for the first case) or Integer.MAX_VALUE
(for the other case).
You should optimize the check over inputB
, so that it is fast. For this, you could create a HashSet
from inputB
.
This is the code:
Set<String> set = new HashSet<>(inputB);
Collections.sort(inputA, Comparator.comparingInt(a -> set.contains(a.getName()) ?
a.getAge() :
Integer.MAX_VALUE));
This works, as long as you don't have an age that is equal to Integer.MAX_VALUE
.
The idea is that you always compare by age, but if an element doesn't belong to inputB
, you turn the age into Integer.MAX_VALUE
. This will have two effects: first, it will make elements not contained in inputB
appear at the bottom; second, as you always return Integer.MAX_VALUE
, the order of the inputA
list is preserved, because Collections.sort
implements a stable sort.