Java List 集合去重:基于特定字段的 Stream API 实现
可以使用 Java 8 的 Stream API 来根据特定字段对 List 集合进行去重操作。以下是一个示例代码:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person('John', 25));
personList.add(new Person('John', 30));
personList.add(new Person('Alice', 28));
personList.add(new Person('Bob', 25));
personList.add(new Person('Bob', 25));
List<Person> distinctPersonList = personList.stream()
.collect(Collectors.toMap(Person::getName, person -> person, (p1, p2) -> p1))
.values()
.stream()
.collect(Collectors.toList());
for (Person person : distinctPersonList) {
System.out.println(person.getName() + ' ' + person.getAge());
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
上述代码中,我们首先使用 Collectors.toMap() 方法将 List 集合转换为 Map,其中键是 Person 对象的 name 字段,值是 Person 对象本身。在转换过程中,如果出现重复的键,则使用 p1 -> p1 的 lambda 表达式保留第一个 Person 对象。然后,我们通过 values() 方法获取去重后的 Person 对象集合,并最终通过 Collectors.toList() 方法将其转换为 List 集合。
运行上述代码,输出为:
John 25
Alice 28
Bob 25
原文地址: https://www.cveoy.top/t/topic/qolq 著作权归作者所有。请勿转载和采集!