Java 8 Lambda 根据属性去重
程序员文章站
2022-06-07 13:14:22
...
Java 8 Lambda 根据属性去重
示例
Student 类
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class DistinctByFieldTest {
public static void main(String[] args) {
Student stu1 = new Student();
stu1.setName("小张");
stu1.setAge(22);
Student stu2 = new Student();
stu2.setName("小张");
stu2.setAge(25);
Student stu3 = new Student();
stu3.setName("小王");
stu3.setAge(19);
List<Student> students = new ArrayList();
students.add(stu1);
students.add(stu2);
students.add(stu3);
System.out.println("去重前:");
students.stream().forEach(x->System.out.println(x.toString()));
System.out.println("去重后");
students.stream().filter(distinctByField(student -> student.getName())).forEach(x->System.out.println(x.toString()));
}
/**
* 根据属性去重
* @param fieldExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctByField(Function<? super T,?> fieldExtractor){
Map<Object,Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(fieldExtractor.apply(t), Boolean.TRUE) == null;
}
}
推荐阅读
-
Java8利用stream的distinct()方法对list集合中的对象去重和抽取属性去重
-
C#NPOI.RabbitMQ.EF.Attribute.HttpRuntime.Cache.AD域.List
根据指定字段去重.前端JQuery.Cache.I18N(多语言).data-xx(自定义属性) -
JAVA 8 lambda 表达式实现按某个属性值查找集合中符合条件的所有对象并求和
-
java8 Stream 一行代码实现列表去重
-
java8 Stream 一行代码实现列表去重
-
Java8-Stream流操作List去重distinct、和指定字段去重(完整实例讲解)
-
List用法:根据对象属性排序、筛选、去重
-
java集合通过对象属性进行去重
-
【Java用法】java 8两个List集合取交集、并集、差集、去重并集
-
Java8使用stream实现list中对象属性的合并(去重并求和)