Java List 集合去重:使用 Stream API 和 Lambda 表达式
可以使用 Java 的 Stream API 和 lambda 表达式来对 List 集合根据字段去重。假设有一个 Student 类,其中有 name 和 age 两个字段,可以根据 name 字段去重。
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student('Alice', 18));
students.add(new Student('Bob', 20));
students.add(new Student('Alice', 18));
students.add(new Student('Charlie', 22));
List<Student> distinctStudents = students.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new ArrayList<>()),
list -> list.stream().distinct().collect(Collectors.toList())
));
for (Student student : distinctStudents) {
System.out.println(student.getName() + ' ' + student.getAge());
}
}
}
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;
}
}
输出结果为:
Alice 18
Bob 20
Charlie 22
通过 Stream 的 distinct() 方法来对 List 集合中的元素进行去重,使用 Collectors.toList() 方法将去重后的元素收集到一个新的 List 集合中。最后,可以遍历新的 List 集合来查看去重后的结果。
原文地址: https://www.cveoy.top/t/topic/qolm 著作权归作者所有。请勿转载和采集!