import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class Person {
private int id;
private String name;
// Constructors, getters, and setters
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Person{id=" + id + ", name='" + name + "'}";
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person(1, "Alice"));
people.add(new Person(2, "Bob"));
people.add(new Person(1, "Charlie"));
people.add(new Person(3, "Alice"));
// 去重逻辑
List<Person> distinctPeople = people.stream()
.filter(distinctByKey(Person::getId))
.collect(Collectors.toList());
distinctPeople.forEach(System.out::println);
}
/**
* 创建一个 Predicate,根据提供的键提取器去重
*/
public static <T> java.util.function.Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
打印结果:
Person{id=1, name='Alice'}
Person{id=2, name='Bob'}
Person{id=3, name='Alice'}