JavajavaJava集合操作
DreamCollector一、初衷
经常会遇到一些需要处理两集合的并集、交集之类的,可以码住收藏起来,说不定你会用的上~
二、相关依赖
1 2 3 4 5 6 7 8 9 10 11 12 13
| <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency>
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.11</version> </dependency>
|
三、例子
以下list集合的创建都是用的hutool
的CollUtil
,可自行替换java原生list创建
1. 并集
AUB 读作”A并B”,例子:{3,5}U{2,3,4,6}= {2,3,4,5,6}
1 2 3 4 5 6 7 8
| public static void main(String[] args) { List<Integer> list1 = CollUtil.newArrayList(3, 5); List<Integer> list2 = CollUtil.newArrayList(2, 3, 4, 6);
System.out.println("Apache并集:" + CollectionUtils.union(list1, list2)); System.out.println("Hutool并集:" + CollUtil.union(list1, list2)); }
|
2. 交集
A∩B 读作”A交B”,例子:A={1,2,3,4,5},B={3,4,5,6,8},A∩B={3,4,5}
1 2 3 4 5 6 7 8
| public static void main(String[] args) { List<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5); List<Integer> list2 = CollUtil.newArrayList(3, 4, 5, 6, 8);
System.out.println("Apache交集:" + CollectionUtils.intersection(list1, list2)); System.out.println("Hutool交集:" + CollUtil.intersection(list1, list2)); }
|
3. 补集
∁UA读作”集合A相对于集合B的补集”,简单来说是将两个集合合并之后剔除后者集合中的元素,例子:A={1,2,3,4,5},B={3,4,5,6,8},∁UA={1,2,6,8}
1 2 3 4 5 6 7 8 9 10 11 12
| public static void main(String[] args) { List<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5); List<Integer> list2 = CollUtil.newArrayList(3, 4, 5, 6, 8);
System.out.println("Apache补集:" + CollectionUtils.disjunction(list1, list2));
List<Integer> complement = new ArrayList<>(list1); complement.removeAll(list2); System.out.println("Hutool交集:" + complement); }
|
4. 差集
A−B读作A相对于B的差集,简单来说就是包含了在 A 中,但不在B中的元素的集合,例子:A={1,2,3,4,5},B={3,4,5,6,8},A-B={1,2}
1 2 3 4 5 6 7 8 9 10 11 12 13
| public static void main(String[] args) { List<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5); List<Integer> list2 = CollUtil.newArrayList(3, 4, 5, 6, 8);
System.out.println("list1的差集:" + CollectionUtils.subtract(list1, list2)); System.out.println("list2的差集:" + CollectionUtils.subtract(list2, list1));
System.out.println("list1的差集:" + CollUtil.subtract(list1, list2)); System.out.println("list2的差集:" + CollUtil.subtract(list2, list1)); }
|