基本概念
為了便於理解,下面首先介紹集合的三個基本操作:並集、交集和補集。
並集:以屬於A或屬於B的元素為元素的集合稱為A與B的並(集),記作A∪B(或B∪A),讀作“A並B”(或“B並A”),即A∪B={x|x∈A,或x∈B}。
交集: 以屬於A且屬於B的元素為元素的集合稱為A與B的交(集),記作A∩B(或B∩A),讀作“A交B”(或“B交A”),即A∩B={x|x∈A,且x∈B}。
在集合論和數學的其他分支中,存在補集的兩種定義:相對補集和絕對補集。
絕對補集:屬於全集U不屬於集合A的元素組成的集合稱為集合A的補集,記作CuA,即CuA={x|x∈U,且x不屬於A}。補集一般指絕對補集。
相對補集(差集):若A 和B 是集合,則A 在B 中的相對補集是這樣一個集合:其元素屬於B但不屬於A,B -A = { x| x∈B且x∉A}。
舉例:令集合A={1,2,3,4,5},集合B={1,2,3,10},則差集:B-A={10}。
在介紹集合實現方法之前,先介紹一下本文要用到的包:
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;
本文基於Java 8進行測試,采用的Guava版本為
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>29.0-jre</version> </dependency>
Jdk中的操作
定義兩個Integer類型的非空集合set1和set2,則在使用JDK中的方法,可以實現集合的交集、並集和差集,方法如下:
- 交集 set1.retainAll(set2);
- 並集 set1.addAll(set2);
- 差集 or 補集 set1.removeAll(set2)。
溫馨提示,它們都是把結果集記錄在set1中,使用的時候需要留意。
Guava Sets操作
@Test public void setOperation() { Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5); Set<Integer> set2 = Sets.newHashSet(3, 4, 5, 6, 7, 9); Sets.SetView<Integer> intersection = Sets.intersection(set1, set2); LOGGER.info("交集為:{}", intersection.toString());//[3, 4, 5]
Sets.SetView<Integer> union = Sets.union(set1, set2); LOGGER.info("並集為:{}", union.toString());//[1, 2, 3, 4, 5, 6, 7, 9]
Sets.SetView<Integer> diff = Sets.difference(set1, set2); LOGGER.info("差集為:{}", diff.toString());//[1, 2]
set1.retainAll(set2); LOGGER.info("jdk中求交集:{}", set1); }
Apache CollectionUtils
org.apache.commons.collections4.CollectionUtils同樣實現了集合的交集、並集和差集,方法如下:
@Test public void CollectionUtilsOperation() { Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5); Set<Integer> set2 = Sets.newHashSet(3, 4, 5, 6, 7, 9); Collection<Integer> col = CollectionUtils.retainAll(set1, set2); LOGGER.info("交集為:{}", col.toString()); col = CollectionUtils.union(set1, set2); LOGGER.info("並集為:{}", col.toString()); col = CollectionUtils.subtract(set1, set2); LOGGER.info("補集為:{}", col.toString()); }
Reference
https://zhidao.baidu.com/question/116778634.html