I have list of objects. Assuming the structure of object is as follows.
class Test {
Int id;
String y;
}
Given a list 'testList' with four instances of Test (let's call them t1, t2, t3, t4).
Requirement is to obtain a list where only the items where the field 'y' is unique are retained. Each entry which has a duplicated value should be removed.
In the above case, assuming that t3 and t4 contains the same value of 'y', the result should be t1 and t2.
One solution is to first create a hash map:
Map<String, List<Test>> yTestMap = new HashMap();
and use the field as key, adding each object that matches the key
Then loop through the HashMap entry set and where ever the value list contains more than one element remove those Test instances from the actual list.
for (List<Test> duplicateTestList : yTestMap.values())
{
testList.removeAll(duplicateTestList);
}
Could you please suggest a more coincise way, maybe using Java 8 streams?