zoukankan      html  css  js  c++  java
  • 自定义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; } }
  • 相关阅读:
    Linq to Sql学习总结1
    SQL相关
    C#各种小知识点总结
    Ext.Net学习笔记
    ASP.NET MVC3入门学习总结
    leetcode-剑指67-OK
    leetcode-剑指44-OK
    leetcode-剑指51-OK
    leetcode-剑指32-III-OK
    leetcode-剑指49-OK
  • 原文地址:https://www.cnblogs.com/frankyou/p/13321024.html
Copyright © 2011-2022 走看看