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; } }
  • 相关阅读:
    自编游戏
    宣言
    Leetcode: 12. Integer to Roman
    Leetcode: 11. Container With Most Water
    Leetcode: 10. Regular Expression Matching
    网络编程:listen函数
    网络编程:connect函数
    Leetcode: 9. Palindrome Number
    Leetcode: 8. String to Integer (atoi)
    Leetcode: 7. Reverse Integer
  • 原文地址:https://www.cnblogs.com/frankyou/p/13321024.html
Copyright © 2011-2022 走看看