写在前面
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);
}