Java 中集合1存id集合2也存入id遍历集合找到集合1中id 在集合2中没有的id
可以使用循环遍历集合1中的每一个元素,然后判断该元素是否存在于集合2中。如果不存在,就将该元素添加到一个新的集合中,最后返回这个新的集合即可。
代码示例:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> collection1 = new ArrayList<>();
collection1.add(1);
collection1.add(2);
collection1.add(3);
collection1.add(4);
List<Integer> collection2 = new ArrayList<>();
collection2.add(3);
collection2.add(4);
collection2.add(5);
collection2.add(6);
List<Integer> result = findMissingIds(collection1, collection2);
System.out.println("Missing ids: " + result);
}
public static List<Integer> findMissingIds(List<Integer> collection1, List<Integer> collection2) {
List<Integer> result = new ArrayList<>();
for (Integer id : collection1) {
if (!collection2.contains(id)) {
result.add(id);
}
}
return result;
}
}
输出结果:
Missing ids: [1, 2]
在上面的示例中,集合1中的元素是1、2、3、4,集合2中的元素是3、4、5、6。通过遍历集合1,发现集合1中的id 1和2在集合2中不存在,所以最后返回的结果是[1, 2]
原文地址: http://www.cveoy.top/t/topic/iNrr 著作权归作者所有。请勿转载和采集!