问题
I have list of objects. Assuming the structure of object is as follows.
class Test {
Int id;
String y;
}
A 'testList' has four instances of Test class which are t1, t2, t3, t4. Requirement is the if multiple instances has the same value for field 'y', they all should be removed from the list. Duplicate values is considered as error scenario and those instances are dealt separately.
For instance in the above case if instance t3 and t4 has same value for 'y' field the processed list should only contain t1 and t2.
The solution I am thinking is create below HashMap from the given List;
Map<String, List<Test>> yTestMap = new HashMap();
where key is the value of 'y' field.
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);
}
I am not sure if this efficient solution for this problem. As the remove operation on a list can be expensive. Also I am creating additional Map data structure. And looping twice, once on the original list to create the Map and then on the map to remove duplicates.
Could you please suggest a better way. May be Java 8 has better way of implementing this.
来源:https://stackoverflow.com/questions/62676162/efficient-way-of-remove-any-element-which-repeats-more-than-once-including-the