stream流根据集合中的元素的属性进行去重的方法
阅读原文时间:2023年08月25日阅读:1

public class StreamListTest {
public static void main(String[] args) {
    
List studentList = new ArrayList<>();
studentList.add(new Student("1","zhangsan"));
studentList.add(new Student("1","zhangsan"));
studentList.add(new Student("1","赵六"));
studentList.add(new Student("2","wangwu"));
studentList.add(new Student("3","超仔"));

    List<Student> collect = studentList.stream().distinct().collect(Collectors.toList());  
    collect.forEach(System.out::println);

    System.out.println("-----------------------以下是根据对象中的某个属性进行去重");  
    List<Student> students = studentList.stream().collect(  
            Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(  
                    Comparator.comparing(Student::getStuNo))),ArrayList::new));

    students.forEach(System.out::println);

}  

}

输出结果:

Student(stuNo=1, name=zhangsan)
Student(stuNo=1, name=赵六)
Student(stuNo=2, name=wangwu)
Student(stuNo=3, name=超仔)
-----------------------以下是根据对象中的某个属性进行去重
Student(stuNo=1, name=zhangsan)
Student(stuNo=2, name=wangwu)
Student(stuNo=3, name=超仔)

这里可以看到完美根据学生的stuNo去重,如果只是使用distinct()方法去重的只是相同的元素,第二种方法根据某个属性来去重,完美达成。

实体类

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