根据对象属性的某个字段对其进行去重操作
@Data
class Person {
private int id;
private String name;
}
public class Main {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob"),
new Person(1, "Alice"),
new Person(3, "Charlie")
);
Collection<Person> distinctPeople = people.stream()
.collect(Collectors.toMap(
Person::getId,
Function.identity(),
(existing, replacement) -> existing))
.values();
Collection<Person> distinctPeople = people.stream()
.collect(Collectors.toMap(
Person::getId,
Function.identity(),
(existing, replacement) -> replacement))
.values();
distinctPeople.forEach(p -> System.out.println(p.getId() + ": " + p.getName()));
}
}
System.out.println(people.stream().collect(Collectors.toMap(Person::getId, Function.identity(),
(existing, replacement) -> existing)).values().stream().map(Person::getId).collect(Collectors.joining(",")));