问题描述
我有一个 ArrayList,它的每个元素都是 DataType 类型,其中 DataType 是一个类:
I have an ArrayList whose each element is of type DataType, where DataType is a class:
class DataType{
String dId;
String dType;
String rId;
}
我需要从列表中删除所有这些元素,其 rId 等于任何其他元素的 dID.即,如果数据类型 D1 的 dID 值为abc",而数据类型 D2 的 rID 值为abc",则从列表中删除 D1 和 D2.
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.
推荐答案
最简单的方法是遍历列表一次并创建一个 HashMap>
.您将每个对象映射到它们的 dID
,形成主键.
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.
之后你可以遍历你的ArrayList
,检查当前对象的rId
,看看它是否在HashMap
中.HashMap
的查找时间为 O(1),所以这应该不是问题.如果该值存在,则删除当前值(您正在使用 Iterator
来防止 ConcurrentModificationException
)并删除键值的值部分内的对象也可以配对.
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.
确保您已正确实现.equals(Object o)
和.hashcode()
.
Make sure you have correctly implemented .equals(Object o)
and .hashcode()
.
这篇关于根据条件从数组列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!