Efficient way of remove any element which repeats more than once (including the first instance) in a list in Java

◇◆丶佛笑我妖孽 提交于 2020-07-08 03:45:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!