java - 如何检查一个元素是否存在于另一个Arraylist中
问题描述
例如我们有两个 ArrayList
ArrayList<Integer> first = new ArrayList<>();
ArrayList<Integer> second = new ArrayList<>();
假设我们向它们添加了一些数字:
first.add(1);
first.add(2);
second.add(2);
second.add(3);
以及如何在这里检查条件,例如:
if(first.contains(second(element))){cnt++;(just increment hypothetical counter)}
谢谢
解决方案
您可以使用Stream
API 过滤和计算第二个列表中的元素。
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> first = new ArrayList<>();
ArrayList<Integer> second = new ArrayList<>();
first.add(1);
first.add(2);
second.add(2);
second.add(3);
second.add(2);
first.forEach(n -> System.out
.println(n + " exists " + second.stream().filter(e -> e == n).count() + " times in the second list"));
}
}
输出:
1 exists 0 times in the second list
2 exists 2 times in the second list
或者,您可以使用在列表中Collections#frequency
打印列表中每个数字的频率:first
second
for (Integer x : first) {
System.out.println(x + " exists " + Collections.frequency(second, x) + " times in the second list");
}
或者,您可以使用嵌套循环来迭代列表,second
对于列表中的每个数字,first
:
for (Integer x : first) {
int count = 0;
for (Integer y : second) {
if (x == y)
count++;
}
System.out.println(x + " exists " + count + " times in the second list");
}
推荐阅读
- python - 为什么 os.path.normpath 不删除第一个 //?
- postgresql - Postgresql:EXECUTE sql_cmd 与 CREATE TEMP TABLE temp_tbl AS SELECT 合并
- amazon-web-services - AWS ECS:通过 Cloudformation 创建 ECS 服务时出现 IAM 相关错误
- python-3.x - 将原始 Scapy 数据解码为人类可读的
- python - Python语音识别速度变慢
- .net - Datagrid 单元格中的文本格式
- php - 尝试更新联系人记录,但我获得执行操作的权限被拒绝 id
- c++ - 您是否使用 cv::calibrateCamera() 获得与使用 cv::fisheye::calibrate() 相同的相机矩阵结果
- python - 带有变量的字典的索引字典
- angular - InvalidValueError:在属性来源中:不是字符串;而不是 LatLng 或 LatLngLiteral:不是对象;而不是一个对象