java - Sets/Lists之间的循环和操作
问题描述
我很难为这篇文章起个名字。基本上,我有两组:让我们称之为A
和B
.
我想做以下事情(\
代表除外):
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);
但这似乎太慢了。这个函数应该每秒被调用数百次,并且集合可以包含数百个对象。
实现这一目标的有效方法是什么?
解决方案
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);
推荐阅读
- php - PHP 7.2 - 包含文件无法访问另一个包含文件
- json - 使用python将带有多个工作表的大文件excel读取到json
- vba - Powerpoint VBA 演示文稿文件名
- mysql - 如何为多个用户使用单个表
- python - 如何为逻辑回归提供正确的初始猜测和界限?
- recursion - 如何在 fortran 中完成递归二进制搜索?
- c# - 如何在数据表中将十进制值显示到小数点后 2 位以在数据网格中显示
- php - MYSQL动态插入INTERVAL DAY数?
- android - Android Studio 不显示我设计的屏幕,而是来自另一个项目的旧屏幕
- verilog - 输出数组不会采用数组寄存器的值