集合操作交并补的三种Java实现

基本概念

  为了便于理解,下面首先介绍集合的三个基本操作:并集、交集和补集。

  并集:以属于A或属于B的元素为元素的集合称为AB的并(集),记作AB(或BA),读作“AB”(或“BA”),即AB={x|xA,xB}

   交集 以属于A且属于B的元素为元素的集合称为AB的交(集),记作AB(或BA),读作“AB”(或“BA”),即AB={x|xA,xB}

      在集合论和数学的其他分支中,存在补集的两种定义:相对补集和绝对补集。

  绝对补集:属于全集U不属于集合A的元素组成的集合称为集合A的补集,记作CuA,即CuA={x|xU,x不属于A}。补集一般指绝对补集。

        相对补集差集):若A 和B 是集合,则A 在B 中的相对补集是这样一个集合:其元素属于B但不属于A,B -A = { x| x∈B且x∉A}。

      举例:令集合A={12345}集合B={12310}差集: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中的方法,可以实现集合的交集、并集和差集,方法如下:

  1. 交集 set1.retainAll(set2);
  2. 并集 set1.addAll(set2);
  3. 差集 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

原文地址:https://www.cnblogs.com/east7/p/12897169.html