java stream 去重_Stream系列(七)distinct方法使用

#java##stream##distinct#

去重

视频讲解 https://www.bilibili.com/video/av77530685/

74a1beb87f3b27308cbc5718a07216c9.png

EmployeeTestCase.java

package 

BaseTest.java

package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class BaseTest {
    protected static final List<Employee> list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));

    protected static final List<List<Employee>> listFlat = Arrays.asList(
            Arrays.asList(new Employee(1, "Alex", 1000),
                    new Employee(2, "Michael", 2000)),
            Arrays.asList(new Employee(3, "Jack", 1500),
                    new Employee(4, "Owen", 1500)),
            Arrays.asList(new Employee(5, "Denny", 2000)));
}

关注公众号,坚持每天3分钟视频学习

39382509788e4fbd33aaff672d73cd80.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您需要在 Stream 中根据某个子属性进行去重操作,可以使用 `distinct()` 方法的重载版本,该版本接受一个自定义的 `hashCode()` 方法和 `equals()` 方法实现作为参数。具体实现步骤如下: 1. 定义一个包含多个重复元素的对象集合,假设该集合中的元素类型为 `Person`,每个 `Person` 对象包含一个字符串类型的属性 `name` 和一个整数类型的属性 `age`。 2. 使用 `stream()` 方法将该集合转换为一个 Stream 对象。 3. 调用 `distinct()` 方法,并将其参数设置为一个自定义的 `hashCode()` 方法和 `equals()` 方法实现。在 `hashCode()` 方法和 `equals()` 方法中,分别使用需要进行去重的子属性来计算对象的哈希值和进行对象比较。 4. 使用 `collect(Collectors.toList())` 方法去重后的元素重新收集到一个 List 集合中。 具体代码实现如下: ```java List<Person> personList = Arrays.asList( new Person("Tom", 20), new Person("Jerry", 30), new Person("Tom", 25), new Person("Alice", 25) ); List<Person> distinctPersonList = personList.stream().distinct() .collect(Collectors.toList()); System.out.println(distinctPersonList); // 自定义 Person 类 class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } // 重写 hashCode() 和 equals() 方法使用 name 属性进行比较 @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Person)) { return false; } Person other = (Person) obj; return this.name.equals(other.name); } } ``` 上述代码中,定义了一个包含多个重复元素的 `Person` 对象集合 `personList`,其中的 `Person` 对象使用 `name` 属性进行比较。接着使用 `stream()` 方法将其转换为一个 Stream 对象,然后调用 `distinct()` 方法,并将其参数设置为一个自定义的 `hashCode()` 方法和 `equals()` 方法实现。在 `hashCode()` 方法和 `equals()` 方法中,分别使用 `name` 属性来计算对象的哈希值和进行对象比较。最终使用 `collect(Collectors.toList())` 方法去重后的元素重新收集到一个 List 集合中,得到的 `distinctPersonList` 集合中只包含了不重复的 `Person` 对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值