我有一个 List
的对象。我想遍历这个对象列表并根据条件处理一些对象子集,最后创建一个新的对象列表,其中一些已处理的对象被删除。
执行此操作的最佳方法是什么?
例子:
实物:List<Cars>
- 遍历此列表并找到
Cars
以同样的速度。 - 在较小的一组
Cars
中, 同型号的要淘汰。 - 最终在消除后我得到了新列表。
最佳答案
谷歌 Guava libraries有:
Iterables.filter(cars, new Predicate<Car>() {
@Override
public boolean apply(Car car) {
//return true or false depending on whether you
// want this car to remain in the list
}
}
您还可以使用中间 Set
- 即
cars = new ArrayList<Car>(new HashSet<Car>(cars));
您在何处正确实现了 hashCode
和 equals
。如果这是您汽车的标识,则此选项可行。
您还可以使用迭代器:
for (Iterator<Car> it = cars.iterator(); it.hasNext();) {
Car car = it.next();
if (conditions here) {
it.remove();
}
}
顺便说一句,我知道上面的例子并没有完全解决你的问题——你仍然应该考虑在外循环中迭代什么。
关于java - 迭代和处理 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3717939/