对象list根据某一属性进行去重 java
可以使用HashSet来实现对象列表根据某一属性进行去重。
具体步骤如下:
-
创建一个HashSet对象,用于存储去重后的对象列表。
-
遍历原始对象列表,对于每个对象,获取需要进行去重的属性值。
-
判断HashSet中是否已经包含该属性值,如果不包含,则将该对象添加到HashSet中。
-
最后,将HashSet转换为List,即为去重后的对象列表。
以下是一个示例代码:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class ObjectListDeduplication {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 20));
personList.add(new Person("Bob", 25));
personList.add(new Person("Alice", 20));
personList.add(new Person("Charlie", 30));
List<Person> deduplicatedList = deduplicateByProperty(personList, "name");
for (Person person : deduplicatedList) {
System.out.println(person);
}
}
public static List<Person> deduplicateByProperty(List<Person> personList, String property) {
HashSet<Object> set = new HashSet<>();
List<Person> deduplicatedList = new ArrayList<>();
for (Person person : personList) {
Object propertyValue = getProperty(person, property);
if (!set.contains(propertyValue)) {
set.add(propertyValue);
deduplicatedList.add(person);
}
}
return deduplicatedList;
}
public static Object getProperty(Person person, String property) {
switch (property) {
case "name":
return person.getName();
case "age":
return person.getAge();
// 可以根据需要添加其他属性的处理逻辑
default:
throw new IllegalArgumentException("Invalid property: " + property);
}
}
static 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 +
'}';
}
}
}
输出结果为:
Person{name='Alice', age=20}
Person{name='Bob', age=25}
Person{name='Charlie', age=30}
``
原文地址: http://www.cveoy.top/t/topic/iqC6 著作权归作者所有。请勿转载和采集!