对象list根据某一属性进行去重 java8
可以使用Java 8的Stream API来对对象列表根据某一属性进行去重。下面是一个示例代码:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
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;
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("John", 25));
people.add(new Person("John", 30));
people.add(new Person("Mary", 28));
people.add(new Person("Mary", 35));
people.add(new Person("John", 25));
List<Person> distinctPeople = people.stream()
.collect(Collectors.groupingBy(Person::getName))
.values()
.stream()
.map(group -> group.get(0))
.collect(Collectors.toList());
distinctPeople.forEach(person -> System.out.println(person.getName() + " - " + person.getAge()));
}
}
输出结果为:
John - 25
Mary - 28
``
原文地址: https://www.cveoy.top/t/topic/iqDb 著作权归作者所有。请勿转载和采集!