java8 lamda集合 根据对象的多个属性去重
时间: 2023-08-11 08:03:17 浏览: 65
和根据单个属性去重类似,我们可以使用Java 8的Lambda表达式和Stream API实现根据对象的多个属性去重。
假设我们有一个Person类,其中包含属性name和age,我们需要根据name和age属性去重,可以按照以下步骤进行操作:
1. 创建一个List<Person>对象,包含多个Person对象,例如:
```
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 20));
personList.add(new Person("Bob", 22));
personList.add(new Person("Alice", 18));
personList.add(new Person("Bob", 22));
```
2. 使用Stream API调用distinct()方法,并传入一个Lambda表达式,以根据name和age属性去重,例如:
```
List<Person> distinctList = personList.stream()
.filter(distinctByKeys(Person::getName, Person::getAge))
.collect(Collectors.toList());
```
3. 在distinctByKeys()方法中,使用一个Map对象来存储已经出现过的name和age值,实现去重操作,例如:
```
public static <T> Predicate<T> distinctByKeys(Function<? super T, ?>... keyExtractors) {
final Map<List<?>, Boolean> seen = new ConcurrentHashMap<>();
return t -> {
final List<?> keys = Arrays.stream(keyExtractors)
.map(ke -> ke.apply(t))
.collect(Collectors.toList());
return seen.putIfAbsent(keys, Boolean.TRUE) == null;
};
}
```
这样,我们就可以根据对象的多个属性去重,得到一个去重后的List对象。