泛型list根据字段去重
时间: 2023-09-19 10:10:12 浏览: 89
您好,可以使用Java8的Stream API和Lambda表达式来实现泛型list根据字段去重的操作。具体实现方法如下:
```java
public static <T> List<T> distinctByKey(List<T> list, Function<? super T, ?> keyExtractor) {
return list.stream().filter(distinctByKey(keyExtractor)).collect(Collectors.toList());
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
```
您可以将需要去重的字段作为keyExtractor参数传递给distinctByKey方法,例如:
```java
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 18));
students.add(new Student("Jack", 20));
students.add(new Student("Tom", 21));
List<Student> distinctStudents = distinctByKey(students, Student::getName);
System.out.println(distinctStudents);
```
上述示例代码将根据Student对象的name字段进行去重操作,并输出去重后的结果。
希望我的回答可以帮到您,谢谢!
阅读全文