首页 > 解决方案 > Sets/Lists之间的循环和操作

问题描述

我很难为这篇文章起个名字。基本上,我有两组:让我们称之为AB.

我想做以下事情(\代表除外):

C = A\B
loop through C;
D = B\A
loop through D;
loop through B;

我的第一次成功尝试是:

// B and A are lists

List<T> C = new LinkedList<>(A);
C.removeAll(B);
for (T other : C)
    operationX(other);

List<T> D = new LinkedList<>(B);
D.removeAll(A);
for (T other : D)
    operationY(other);

for (T other : B)
    operationZ(other);

但这似乎太慢了。这个函数应该每秒被调用数百次,并且集合可以包含数百个对象。

实现这一目标的有效方法是什么?

标签: javasetiteration

解决方案


C如果您只是打算遍历它,则根本不需要创建。您可以简单地过滤掉A其中包含的每个元素B,然后调用operationX每个过滤后的元素:

Set<T> bSet = new HashSet<>(B);

A.stream()
 .filter(a -> !bSet.contains(a))
 .forEach(this::operationX);

假设里面可以有重复的元素,B并且operationY需要对所有重复的元素进行调用,那么我们可以使用如下:

Set<T> aSet = new HashSet<>(A);

B.stream()
 .filter(b -> !aSet.contains(b))
 .forEach(this::operationY);

B.forEach(this::operationZ);

如果即使存在重复项也operationY只需要为每个元素调用一次B,那么我建议使用下面的代码:

bSet.removeAll(A);
bSet.forEach(this::operationY);
B.forEach(this::operationZ);

推荐阅读