一篇文章教你学会:对Java集合进行并集,交集,差集运算

简介: 一篇文章教你学会:对Java集合进行并集,交集,差集运算

废话不多,直接上代码:

264419ecc59ecd9600e4fd2c3d05939.png

1:新建一个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
   private Integer id;
   private String name;
}

2:准备好数据

public class tset {
   public static void main(String[] args) {
      List<Student> AList = new ArrayList<>(Arrays.asList(
              new Student(1,"张三"),
              new Student(2,"李四"),
              new Student(3,"王五")
      ));
      List<Student> BList = new ArrayList<>(Arrays.asList(
              new Student(2,"李四"),
              new Student(3,"王五"),
              new Student(4,"赵六")
      ));
  }

3:使用stream 流求

3.1 并集

Stream的concat() 方法
      //并集  使用Stream的concat()方法将两个集合合并为一个流,
      //然后使用distinct()方法去除重复元素即可求得并集
      List<Student> unionList = Stream.concat(AList.stream(), BList.stream())
              .distinct()
              .collect(Collectors.toList());
      System.out.println(unionList);
打印结果:
[Student(id=1, name=张三), 
Student(id=2, name=李四), 
Student(id=3, name=王五),
Student(id=4, name=赵六)]

3.2 交集

//AList 和 BList 元素交集(俩个元素中都有的元素)
      List<Student> studentList = AList.
              stream().
              filter(a ->
                      BList.stream()
                              .map(Student::getId)
                              .anyMatch(id ->
                                      Objects.equals(a.getId(), id)))
.collect(Collectors.toList());
      System.out.println("--------AList 和 BList 元素交集:");
      /**
       * --------AList 和 BList 元素交集:
       * [Student(id=2, name=李四), Student(id=3, name=王五)]
       */
      System.out.println(studentList);

3.3 差集

3.31(第一种)

//BList 和 AList 元素差集  只在B集合中存在,不在A集合中存在
      List<Student> studentList1 = BList.stream()
              .filter(b ->
                      AList.stream()
                              .map(Student::getId)
                              .noneMatch(id -> Objects.equals(b.getId(), id)))
              .collect(Collectors.toList());
      System.out.println("BList 和 AList 元素差集:");
      /**
       * BList 和 AList 元素差集:
       * [Student(id=4, name=赵六)]
       */
      System.out.println(studentList1);

3.32(第二种)

Map<Integer, Student> map = AList.stream()
              .collect(Collectors.toMap(Student::getId, Function.identity(), (k1, k2) -> k2));
      List<Student> studentList2 = BList.stream()
              .filter(b -> !map.containsKey(b.getId())).collect(Collectors.toList());
      System.out.println("BList 和 AList 元素差集:");
      /**
       * BList 和 AList 元素差集:
       * [Student(id=4, name=赵六)]
       */
      System.out.println(studentList2);

4:使用Goole Guava 工程中的sets 工具包

4.1 引入依赖

 

<!-- google java lib -->
  <dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>17.0</version>
  </dependency>

4.2 准备数据

HashSet<Integer> set = Sets.newHashSet(1, 2, 3, 4, 5, 6);
      HashSet<Integer> set2 = Sets.newHashSet( 3, 4, 5, 6,7,8,9);

4.3 并集

Sets.union()

//并集
      Sets.SetView<Integer> setView2 = Sets.union(set, set2);
      /**
       * [1, 2, 3, 4, 5, 6, 7, 8, 9]
       */
      System.out.println(setView2);

4.4 交集

Sets.intersection();

//交集
      Sets.SetView<Integer> setView = Sets.intersection(set, set2);
      /**
       *   [3, 4, 5, 6]
       */
      System.out.println(setView);

4.5 差集

Sets.difference();

//差集
      Sets.SetView<Integer> setView1 = Sets.difference(set, set2);
      /**
       * [1, 2]
       */
      System.out.println(setView1);


目录
相关文章
|
19天前
|
安全 Java API
【Java面试题汇总】Java基础篇——String+集合+泛型+IO+异常+反射(2023版)
String常量池、String、StringBuffer、Stringbuilder有什么区别、List与Set的区别、ArrayList和LinkedList的区别、HashMap底层原理、ConcurrentHashMap、HashMap和Hashtable的区别、泛型擦除、ABA问题、IO多路复用、BIO、NIO、O、异常处理机制、反射
【Java面试题汇总】Java基础篇——String+集合+泛型+IO+异常+反射(2023版)
|
8天前
|
存储 安全 Java
Java 常用集合分类
Java 常用集合分类
13 2
|
2月前
|
Java
用JAVA架建List集合为树形结构的代码方法
这段代码定义了一个表示树形结构的 `Node` 类和一个用于构建树形结构的 `TreeController`。`Node` 类包含基本属性如 `id`、`pid`、`name` 和 `type`,以及子节点列表 `children`。`TreeController` 包含初始化节点列表并将其转换为树形结构的方法。通过过滤和分组操作实现树形结构的构建。详情可见:[代码示例链接1](http://www.zidongmutanji.com/zsjx/43551.html),[代码效果参考链接2](https://www.257342.com/sitemap/post.html)。
31 5
|
1月前
|
Java API 开发者
代码小妙招:用Java轻松获取List交集数据
在Java中获取两个 `List`的交集可以通过 `retainAll`方法和Java 8引入的流操作来实现。使用 `retainAll`方法更为直接,但会修改原始 `List`的内容。而使用流则提供了不修改原始 `List`、更为灵活的处理方式。开发者可以根据具体的需求和场景,选择最适合的方法来实现。了解和掌握这些方法,能够帮助开发者在实际开发中更高效地处理集合相关的问题。
28 1
|
2月前
|
存储 Java 程序员
Java中的集合框架:从入门到精通
【8月更文挑战第30天】在Java的世界里,集合框架是一块基石,它不仅承载着数据的存储和操作,还体现了面向对象编程的精髓。本篇文章将带你遨游Java集合框架的海洋,从基础概念到高级应用,一步步揭示它的奥秘。你将学会如何选择合适的集合类型,掌握集合的遍历技巧,以及理解集合框架背后的设计哲学。让我们一起探索这个强大工具,解锁数据结构的新视角。
|
2月前
|
存储 算法 Java
Java中的集合框架深度解析云上守护:云计算与网络安全的协同进化
【8月更文挑战第29天】在Java的世界中,集合框架是数据结构的代言人。它不仅让数据存储变得优雅而高效,还为程序员提供了一套丰富的工具箱。本文将带你深入理解集合框架的设计哲学,探索其背后的原理,并分享一些实用的使用技巧。无论你是初学者还是资深开发者,这篇文章都将为你打开一扇通往高效编程的大门。
|
2月前
|
存储 算法 Java
Java 中的同步集合和并发集合
【8月更文挑战第22天】
25 5
|
2月前
|
存储 Java
【Java集合类面试二十九】、说一说HashSet的底层结构
HashSet的底层结构是基于HashMap实现的,使用一个初始容量为16和负载因子为0.75的HashMap,其中HashSet元素作为HashMap的key,而value是一个静态的PRESENT对象。
|
2月前
|
Java
【Java集合类面试三十】、BlockingQueue中有哪些方法,为什么这样设计?
BlockingQueue设计了四组不同行为方式的方法用于插入、移除和检查元素,以适应不同的业务场景,包括抛异常、返回特定值、阻塞等待和超时等待,以实现高效的线程间通信。
|
2月前
|
存储 算法 Java
Java中的集合框架深度解析与实践
【8月更文挑战第31天】在Java编程的海洋中,集合框架扮演着不可或缺的角色。本文将带你领略Java集合框架的魅力,从理论到实践,深入浅出地探索List、Set和Map等核心接口的使用技巧。我们将通过具体代码示例,展示如何在日常开发中高效运用这些工具,让你的代码更加优雅和高效。无论你是初学者还是有经验的开发者,这篇文章都将为你打开一扇通往Java集合世界的大门。
下一篇
无影云桌面