Stream流-Java8中通过Stream对列表进行去重的几种方法-《Java笔记》

admin 2025-10-19 02:40:58 编程 来源:ZONE.CI 全球网 0 阅读模式

JavaStream

1、Stream 的distinct()方法

distinct()是Java 8 中 Stream 提供的方法,返回的是由该流中不同元素组成的流。distinct()使用 hashCode()eqauls() 方法来获取不同的元素。因此,需要去重的类必须实现 hashCode()equals() 方法。换句话讲,可以通过重写定制的 hashCode()equals() 方法来达到某些特殊需求的去重。distinct() 方法声明如下:

  1. Stream<T> distinct();

1.1 对于 String 列表的去重

因为 String 类已经覆写了 equals()hashCode() 方法,所以可以去重成功。

  1. @Test
  2. public void listDistinctByStreamDistinct() {
  3. // 1. 对于 String 列表去重
  4. List<String> stringList = new ArrayList<String>() {{
  5. add("A");
  6. add("A");
  7. add("B");
  8. add("B");
  9. add("C");
  10. }};
  11. out.print("去重前:");
  12. for (String s : stringList) {
  13. out.print(s);
  14. }
  15. out.println();
  16. stringList = stringList.stream().distinct().collect(Collectors.toList());
  17. out.print("去重后:");
  18. for (String s : stringList) {
  19. out.print(s);
  20. }
  21. out.println();
  22. }

结果如下:

  1. 去重前:AABBC
  2. 去重后:ABC

1.2 对于实体类列表的去重

注:代码中使用了 Lombok 插件的 @Data解,可自动覆写 equals() 以及 hashCode() 方法。

  1. /**
  2. * 定义一个实体类
  3. */
  4. @Data
  5. public class Student {
  6. private String stuNo;
  7. private String name;
  8. }
  9. @Test
  10. public void listDistinctByStreamDistinct() throws JsonProcessingException {
  11. ObjectMapper objectMapper = new ObjectMapper();
  12. // 1. 对于 Student 列表去重
  13. List<Student> studentList = getStudentList();
  14. out.print("去重前:");
  15. out.println(objectMapper.writeValueAsString(studentList));
  16. studentList = studentList.stream().distinct().collect(Collectors.toList());
  17. out.print("去重后:");
  18. out.println(objectMapper.writeValueAsString(studentList));
  19. }

结果如下:

  1. 去重前:[{"stuNo":"001","name":"Tom"},{"stuNo":"002","name":"Mike"},{"stuNo":"001","name":"Tom"}]
  2. 去重后:[{"stuNo":"001","name":"Tom"},{"stuNo":"002","name":"Mike"}]

2、根据 List<Object> 中 Object 某个属性去重

2.1 新建一个列表出来

  1. @Test
  2. public void distinctByProperty1() throws JsonProcessingException {
  3. // 这里第一种方法我通过新创建一个只有不同元素列表来实现根据对象某个属性去重
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. List<Student> studentList = getStudentList();
  6. out.print("去重前 :");
  7. out.println(objectMapper.writeValueAsString(studentList));
  8. studentList = studentList.stream().distinct().collect(Collectors.toList());
  9. out.print("distinct去重后:");
  10. out.println(objectMapper.writeValueAsString(studentList));
  11. // 这里我们引入了两个静态方法,以及通过 TreeSet<> 来达到获取不同元素的效果
  12. // 1. import static java.util.stream.Collectors.collectingAndThen;
  13. // 2. import static java.util.stream.Collectors.toCollection;
  14. studentList = studentList.stream().collect(
  15. collectingAndThen(
  16. toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new)
  17. );
  18. out.print("根据名字去重后 :");
  19. out.println(objectMapper.writeValueAsString(studentList));
  20. }

结果如下:

  1. 去重前 :[{"stuNo":"001","name":"Tom"},{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
  2. distinct去重后:[{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
  3. 根据名字去重后 :[{"stuNo":"001","name":"Tom"}]

2.2 通过 filter() 方法

首先创建一个方法作为 Stream.filter() 的参数,其返回类型为 Predicate,原理就是判断一个元素能否加入到 Set 中去,代码如下:

  1. private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
  2. Set<Object> seen = ConcurrentHashMap.newKeySet();
  3. return t -> seen.add(keyExtractor.apply(t));
  4. }

使用如下:

  1. @Test
  2. public void distinctByProperty2() throws JsonProcessingException {
  3. // 这里第二种方法我们通过过滤来实现根据对象某个属性去重
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. List<Student> studentList = getStudentList();
  6. out.print("去重前 :");
  7. out.println(objectMapper.writeValueAsString(studentList));
  8. studentList = studentList.stream().distinct().collect(Collectors.toList());
  9. out.print("distinct去重后:");
  10. out.println(objectMapper.writeValueAsString(studentList));
  11. // 这里我们将 distinctByKey() 方法作为 filter() 的参数,过滤掉那些不能加入到 set 的元素
  12. studentList = studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList());
  13. out.print("根据名字去重后 :");
  14. out.println(objectMapper.writeValueAsString(studentList));
  15. }

结果如下:

  1. 去重前 :[{"stuNo":"001","name":"Tom"},{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
  2. distinct去重后:[{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
  3. 根据名字去重后 :[{"stuNo":"001","name":"Tom"}]
以太坊cppgolang区别 编程

以太坊cppgolang区别

以太坊是一种去中心化的开源平台,它采用智能合约技术,旨在构建和运行不受干扰的分布式应用程序。作为目前最受欢迎的区块链平台之一,以太坊提供了多种编程语言的支持,其
progolang 编程

progolang

Go语言(Golang)是由Google开发的一门静态类型编程语言。作为一名专业的Golang开发者,我深知这门语言的优势和特点。在本文中,我将介绍Golang
golangn个发送者 编程

golangn个发送者

Golang是一种开源的编程语言,由Google团队开发,旨在提高程序的并发性和简化软件开发过程。在Go语言中,有时需要向多个接收者发送信息。本文将介绍如何在G
golang技能图谱 编程

golang技能图谱

从互联网行业的快速发展到人工智能技术的日益成熟,各种编程语言也应运而生。而在这众多的编程语言中,Golang(即Go)作为一门强大且高效的开发语言备受关注。Go
评论:0   参与:  6