Remove elements from arraylist based on a condition [closed]

江枫思渺然 提交于 2020-01-17 23:29:52

问题


I have an ArrayList whose each element is of type DataType, where DataType is a class:

class DataType{
 String dId;
 String dType;
 String rId;
}

I need to remove all such elements from the list whose rId is equal to any other element's dID. i.e. if DataType D1 has value of dID as "abc" and DataType D2 has value of rID as "abc", than remove both D1 and D2 from the list.

Could someone please suggest the most appropriate approach for doing this.


回答1:


The easiest would be to traverse the list once and create a HashMap<String, List<DataType>>. You will map every object to their dID which forms the primary key.

After that you can iterate over your ArrayList, check the rId of the current object and see if it's in the HashMap. HashMap has O(1) lookup time so this should be a non issue. If the value is present, remove the current value (you're using an Iterator to prevent a ConcurrentModificationException) and remove the objects inside the value-part of the key-value pair as well.

Make sure you have correctly implemented .equals(Object o) and .hashcode().



来源:https://stackoverflow.com/questions/20602388/remove-elements-from-arraylist-based-on-a-condition

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