stream流根據集合中的元素的屬性進行去重的方法
阿新 • • 發佈:2022-05-07
public class StreamListTest { public static void main(String[] args) { List<Student> 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; }