欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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;
    }
}

相关标签: java lambda