list 集合取交集,并集,差集,不管是在实际项目中还是有一些公司的面试题中,我们总会遇到。最笨的方法就是用 for 循环一一比较,再进行增删操作。可能稍微好一些的方法就是用到了 Java8 的 stream 流来操作, 可以利用 filter / anymath 处理。但其实还有更简单的方法。
假如有2个集合:
1 2 |
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7); |
差集
要在 list1 中得到 list2 中不包含的集合
1 |
list1.removeAll(list2); |
其实 removeAll 可以做到,但是这样就会破坏了原有的 list1,所以最好创建一个新的集合
1 2 |
List<Integer> result = new ArrayList<>(list1); result.removeAll(list2); |
这样 result 就是想要的差集了: 1 2
交集
用 list1 再减去上面得到的差集,不就是交集了吗?
为了不影响原来的 list, 我们依然要创建一个新的集合
1 2 |
List<Integer> result2 = new ArrayList<>(list1); result2.removeAll(result); |
这样 result2 里面存放的就是交集了: 3 4 5
并集
用 list2 加上前面的差集, 不就是并集了吗 ?
1 2 |
List<Integer> result3 = new ArrayList<>(list2); result3.addAll(result); |
这样 result3 就是并集啦: 1 2 3 4 5 6 7
利用第三方库
可以看出利用 list 的 removeAll / addAll 其实就可以做到交集/并集/差集 的计算,但是每次都要新建一个 list 会显得有些麻烦。其实这种常见的场景,第三方库早就有封装了,随便举个例子
1 |
org.apache.commons.collections4.ListUtils |
1 2 3 4 5 6 7 8 9 10 |
// 差集 List<Integer> result = ListUtils.removeAll(list1, list2); // 也是差集方法2 // List<Integer> result = ListUtils.subtract(list1, list2); // 交集 List<Integer> result2 = ListUtils.retainAll(list1, list2); // 也是交集方法2 // List<Integer> result2 = ListUtils.intersection(list1, list2); // 并集 List<Integer> result3 = ListUtils.sum(list1, list2); |
简单易懂