最近接了个很简单的需求,但小名作为一名"有代码洁癖"的小菜鸡,尽管需求很简单,小名也不可能简简单单的就放过它!
需求: 客人使用了id为ListA的集合优惠券,后台限制客人使用了id存在于ListB集合中的优惠券,后续不再发放其他奖励了。
分析: 两个存放id的Long集合若存在交集,就不再发放其他奖励。
所以问题就很简单了,我们只要想办法比较两个集合是否存在交集就可以了:于是我们马上就能能想到的方法:通过for循环逐个元素比较,遇到相同返回有相同的结果;我们也可以通过小名在之前文章提到的lambda表达式提高性能,等。今天小名想分享给大家的是来自“万能的Collections”中的一个静态方法disjoint顾名思义,它是用来判断两个集合"不相交的”的结果,但我们只要对返回结果取反,就可以高效获得我们想要的结果。
为了使得例子看起来清晰些,忽略集合为空情况,大家可以在文末看到所有方法的测试用例:
- 1. for循环
- 2. lambda表达式
- 3. retainAll
- 4. disjoint
- 5. 测试
这里为了看起来清晰些,使用了增强for循环,当然你也可以使用定义变量的普通for循环,这里就不赘述了
public static Boolean forMethod(ListA, List 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(ListA, List B) { List collect = A.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(ListA, List B) { List 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(ListA, List 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()返回的是不相交的,所以结果与其他相反
如若您在文章中发现任何错误的地方,小名希望您可以在评论区给予批评指正欄 如果觉得小名的文章帮助到了您,请关注小名的专栏【日常记错】,支持一下小名,给小名的文章点赞、评论✍、收藏爛谢谢大家啦~♥♥♥



