自定义predicate来对List进行去重

 

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import lombok.Data;

/**
 * @author xfyou
 */
public class Test {

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        Person p1 = new Person();
        p1.setName("Frank");
        personList.add(p1);

        Person p2 = new Person();
        p2.setName("Frank");
        personList.add(p2);

        Person p3 = new Person();
        p3.setName("Tom");
        personList.add(p3);

        personList.stream().filter(distinctByKey(Person::getName)).forEach(c -> System.out.println(c.getName()));
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
     // 这个局部变量必须定义,这个局部变量将会成为下面生成的局部匿名内部类的一个字段(field)
final Set<Object> seen = ConcurrentHashMap.newKeySet(); // 用 lambda 来代替匿名内部类 return t -> seen.add(keyExtractor.apply(t)); } @Data public static class Person { private String name; } }

 

posted @ 2020-07-16 09:49  FrankYou  阅读(175)  评论(0编辑  收藏