java8 list对象根据指定属性去重
可以使用Java 8的Stream API来实现列表对象根据指定属性去重。以下是一个示例代码:
假设有一个Student类:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
现在我们有一个包含多个Student对象的列表,我们要根据name属性去重,可以使用以下代码:
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 21));
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 23));
students.add(new Student("Charlie", 24));
List<Student> uniqueStudents = students.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))),
ArrayList::new
));
uniqueStudents.forEach(student -> System.out.println(student.getName() + " " + student.getAge()));
输出结果为:
Alice 20
Bob 21
Charlie 24
这样就根据name属性去重了列表对象
原文地址: https://www.cveoy.top/t/topic/ixsM 著作权归作者所有。请勿转载和采集!