首页 > 解决方案 > 如何检查一个元素是否存在于另一个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)}

谢谢

标签: javaloopsarraylist

解决方案


您可以使用StreamAPI 过滤和计算第二个列表中的元素。

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打印列表中每个数字的频率:firstsecond

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");
}

推荐阅读