import java.util.*;
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;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Alice", 30), // 重复的对象
new Person("Charlie", 35)
);
// 根据name属性去重
List<Person> distinctPeopleByName = people.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(Person::getName, person -> person, (existing, replacement) -> existing),
map -> new ArrayList<>(map.values())
));
System.out.println("根据name属性去重后的列表:");
distinctPeopleByName.forEach(System.out::println);
// 根据age属性去重
List<Person> distinctPeopleByAge = people.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(Person::getAge, person -> person, (existing, replacement) -> existing),
map -> new ArrayList<>(map.values())
));
System.out.println("根据age属性去重后的列表:");
distinctPeopleByAge.forEach(System.out::println);
}
}
Person类,包含两个属性name和age,并提供了构造函数、getter方法和toString方法。Person对象的列表,其中有一个重复的对象("Alice", 30)。stream()将列表转换为流。Collectors.toMap根据name属性进行分组,确保每个name只保留一个对象。Collectors.collectingAndThen用于在收集完成后将Map转换回List。Collectors.toMap根据age属性进行分组,确保每个age只保留一个对象。List并打印。这段代码展示了如何根据对象的不同属性(如name或age)对列表中的对象进行去重。
上一篇:java关键字有哪些及其作用
下一篇:javalist排序sort降序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站