判断两个集合中是否存在相同元素的4种常用方法(两个集合是否存在交集)
时间:2023-05-24 10:37:01
最近,我收到了一个非常简单的需求,但昵称是一个"有代码洁癖"小菜鸡,虽然需求很简单,小名也不能简单地放过!
需求: 客人使用了id为ListA后台限制客人使用集合优惠券id存在于ListB集中优惠券后续不发放其他奖励。
分析: 两个存放id的Long如果有交集,将不再发放其他奖励。
所以问题很简单,我们只需要找到比较两个集合是否有交集的方法:所以我们可以立即想到:通过for循环逐个比较元素,遇到相同的回报有相同的结果;我们也可以通过前面文章中提到的昵称来比较lambda表达式提高性能,等等。小名今天想和大家分享的是万能Collections一种静态方法disjoint
顾名思义,它被用来判断两个集合"不相交的”结果,但我们只需要返回结果取反,我们可以有效地得到我们想要的结果。
为了使例子看起来清晰,忽略集合为空,您可以在文章末尾看到所有方法的测试用例:
文章目录
-
-
- 1. for循环
- 2. lambda表达式
- 3. retainAll
- 4. disjoint
- 5. 测试
-
1. for循环
为了看起来更清楚,这里使用了增强剂for当然,你也可以使用普通的定义变量for循环,这里就不赘述了。
public static Boolean forMethod(List<Long> A, List<Long> B) {
Boolean flag = false; for (Long idA : A) {
for (Long idB : B) {
if (idA == idB) {
flag = true; } } } return flag; }
2. lambda表达式
public static Boolean lambadaMethod(List<Long> A, List<Long> B) {
List<Long> collect = .stream().filter(item -> B.contains(item)).collect(Collectors.toList()); if (null != collect && collect.size() > 0) {
return true; } else {
return false; } }
3. retainAll
这里需注意的是:使用retainAll会删除A集合中不存在于集合B中的元素,所以为了不修改原集合,我们需要创建一个中间集合
public static Boolean retainAllMethod(List<Long> A, List<Long> B) {
List<Long> res = new ArrayList<>();
res.addAll(A);
res.retainAll(B);
if (res.size() > 0) {
return true;
} else {
return false;
}
}
4. disjoint
disjoint直译:不相交的,所以我们要特别注意,它的结果可能和我们最终想得到的结果相反:
比较两个集合中是否有相同的元素;当两个集合中没有相同元素时返回true,当有相同元素时返回false。
public static Boolean disjointMethod(List<Long> A, List<Long> B) {
boolean disjoint = Collections.disjoint(A, B);
return disjoint;
}
5. 测试
public static void main(String[] args) {
List l1 = new ArrayList<>();
l1.add(7l);
l1.add(2l);
Long[] a1 = {
1l, 2l, 3l, 4l};
List l2 = Arrays.asList(a1);
System.out.println("【集合A】:" + l1);
System.out.println("【集合B】:" + l2);
Boolean forMethod = forMethod(l1, l2);
System.out.println("forMethod结果为:" + forMethod);
Boolean lambadaMethod = lambadaMethod(l1, l2);
System.out.println("lambadaMethod结果为:" + lambadaMethod);
Boolean retainAllMethod = retainAllMethod(l1, l2);
System.out.println("retainAllMethod结果为:" + retainAllMethod);
Boolean disjointMethod = disjointMethod(l1, l2);
System.out.println("disjointMethod结果为:" + disjointMethod);
}
输出结果:
【集合A】:[7, 2]
【集合B】:[1, 2, 3, 4]
forMethod结果为:true
lambadaMethod结果为:true
retainAllMethod结果为:true
disjointMethod结果为:false //disjoint()返回的是不相交的,所以结果与其他相反
如若您在文章中发现任何错误的地方,小名希望您可以在评论区给予批评指正🤝 如果觉得小名的文章帮助到了您,请关注小名的专栏【日常记错】,支持一下小名😄,给小名的文章点赞👍、评论✍、收藏🤞谢谢大家啦~♥♥♥