准备数据
List<Integer> list1 = Lists.newArrayList(1,2,3);List<Integer> list2 = Lists.newArrayList(3,4,5);
1.交集
list1.retainAll(list2);System.out.println("打印结果:"+list1);//打印结果:[3]
CollectionUtils 工具类实现
Collection intersection = CollectionUtils.intersection(list1, list2);System.out.println("test2 交集结果是: " + intersection);//交集结果是:[3]
2.并集
list1.addAll(list2);System.out.println("并集 :" + list1);//并集 :[1, 2, 3, 3, 4, 5]// 并集 去重HashSet<Integer> set = Sets.newHashSet();set.addAll(list1);set.addAll(list2);System.out.println("并集 去重 :" + set);//并集 去重 :[1, 2, 3, 4, 5]
CollectionUtils 工具类实现
Collection union = CollectionUtils.union(list1, list2);System.out.println("并集 去重:" + union);//并集 去重:[1, 2, 3, 4, 5]
3.差集
list1.removeAll(list2);System.out.println("差集: " + list1);//差集: [1, 2]
CollectionUtils 工具类
Collection subtract = CollectionUtils.subtract(list1, list2);System.out.println("差集: " + subtract);//差集: [1, 2]
4.补集,使用 list 循环对比
ArrayList<Integer> destList = Lists.newArrayList();boolean flag = false;for (Integer e1 : list1) {for (Integer e2 : list2) {if(e1.equals(e2)){flag = true;break;}}if (!flag) {destList.add(e1);} else {flag = false;}}// list1 和 list2 换位置对比下flag = false;for (Integer e1 : list2) {for (Integer e2 : list1) {if(e1.equals(e2)){flag = true;break;}}if(!flag){destList.add(e1);}else {flag = false;}}System.out.println("补集:" +destList);//补集:[1, 2, 4, 5]
补集 — 使用Map对比
ArrayList<Integer> destList = Lists.newArrayList();Map<Integer, Integer> map1 = list1.stream().collect(Collectors.toMap(k -> k, v -> v));Map<Integer, Integer> map2 = list2.stream().collect(Collectors.toMap(k -> k, v -> v));map1.forEach((k,v)->{Integer val = map2.get(k);if(null == val){destList.add(k);}});map2.entrySet().stream().forEach(e->{Integer key = e.getKey();Integer val = map1.get(key);if(null == val){destList.add(key);}});System.out.println("补集:" +destList);//补集:[1, 2, 4, 5]
CollectionUtils.disjunction 方法
Collection disjunction = CollectionUtils.disjunction(list1, list2);System.out.println("补集:" +disjunction);//补集:[1, 2, 4, 5]
补集 — 使用 list1 和 list2相互差集,再并集
Collection s1 = CollectionUtils.subtract(list1, list2);Collection s2 = CollectionUtils.subtract(list2, list1);Collection union = CollectionUtils.union(s1, s2);System.out.println("补集 , 2个差集再并集:" +union);//补集:[1, 2, 4, 5]