删除基于条件的ArrayList从要素 [英] Remove elements from arraylist based on a condition

查看:136
本文介绍了删除基于条件的ArrayList从要素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ArrayList的每个元素的类型是数据类型,数据类型的地方是一类的:

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等于任何其他元素的做了列表中删除所有这样的元素。
也就是说,如果数据类型D1有照ABC的值和数据类型D2具有的摆脱为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 ,检查摆脱当前对象的,看看它在在的HashMap 的HashMap 有O(1)查找时间,所以这应该是一个非的问题。如果值是present,删除当前值(您使用的是的Iterator 来prevent一个 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(对象o) .hash code()

这篇关于删除基于条件的ArrayList从要素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆