Thare are two input lists as follows:
inputA = [
{
name: "A",
age: 20
},
{
name: "B",
age: 30
},
{ name: "C",
age: 25
},
{ name: "D",
age: 28
}
]
inputB = ["D", "B"]
My preferred output list must be as follows:
expectedOutput = [
{
name: "D",
age: 28
},
{
name: "B",
age: 30
},
{ name: "A",
age: 20
},
{ name: "C",
age: 25
}
]
What I have done so far looks like below:
AtomicInteger count = new AtomicInteger();
Collections.sort(inputA, Comparator
.comparing(a ->
if (inputB.indexOf(a.getName()) > -1) {
return -1;
}
else {
return count.incrementAndGet();
})
.thenComparingInt(a -> a.getAge()));
The output I am getting is as follows
actualOutput = [
{
name: "D",
age: 28
},
{
name: "B",
age: 30
},
{ name: "C",
age: 25
},
{ name: "A",
age: 20
}
]
Problem is with the elements that doesn't have their name in the list inputB. There order doesn't have the original order in inputA. For the original order to persist { name: "A", age: 20 } should come before { name: "C", age: 25 }
How can i solve this issue while using the comparator chaining strategy?
UPDATE Sorting logic is, if inputA has objects where the names are equal to the inputB list, those elements should come to the top of the inputA and then those elements must be sorted by their age while keeping the original order of the other elements in inputA which are not present in inputB
This is not a possible duplicate, because this question tries to compare two lists and also sort the common elements by a property of an object from the the first list while leaving the rest of the elements in their original order.
.thenComparingIntinstead of justcomparingInt?return count.incrementAndGet();in the else case. That where the issue lies