Java-Stream distinct 去重

写在前面

distinct()返回由该流的不同元素组成的流distinct()是Stream接口的方法。distinct()使用hashCode()equals()方法来获取不同的元素。因此,我们的类必须实现hashCode()equals()方法。

对象去重

代码实例 未重写hashCode()&equals()

public class Student {
   
    private String name;
    private int age;
    private int type;

    public Student() {
   
    }

    public Student(String name, int age, int type) {
   
        this.name = name;
        this.age = age;
        this.type = type;
    }

    @Override
    public String toString() {
   
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", type=" + type +
                '}';
    }

    public static void main(String[] args) {
   
        List<Student> students = Arrays.asList(
                new Student("张三", 18, 1),
                new Student("李四", 20, 1),
                new Student("小明", 22, 3),
                new Student("Jack", 22, 3),
                new Student("Jack", 22, 3)
        );

        // 未重写 hashCode() & equals()
        students.stream().distinct().forEach(System.out::println);

        /** 输出 两个Jack一模一样
         * Student{name='张三', age=18, type=1}
         * Student{name='李四', age=20, type=1}
         * Student{name='小明', age=22, type=3}
         * Student{name='Jack', age=22, type=3}
         * Student{name='Jack', age=22, type=3}
         */
    }
}

重写hashCode()&equals()

public class Student {
   
    private String name;
    private int age;
    private int type;

    public Student() {
   
    }

    public Student(String name, int age, int type) {
   
        this.name = name;
        this.age = age;
        this.type = type;
    }

    @Override
    public String toString() {
   
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", type=" + type +
                '}';
    }

    @Override
    public boolean equals(Object o) {
   
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return age == student.age &&
                type == student.type &&
                Objects.equals(name, student.name);
    }
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值