Lambda表達式對List集合對象屬性進行去重


1.選用Lambda表達簡潔,運行效率更高,其實還是利用了map的特性進行去重
2.distinctByKey()方法,講解下這個方法里的參數內容
(1)首先是Predicate這個返回參數,傳入參數,返回true/false,(可以翻看源碼看下
(2)對於Lambda表達式來說 filter會過濾為false的值,而參數Function是用來代替所傳參數(可以翻看源碼)
(3)創建一個ConcurrentHashMap,是由於流的讀取是基於並發的,這個map集合在基於線程安全的情況下,並發效率更高
(4)
putIfAbsent()使用了map源碼中的方法,大意是 當鍵不存在時,把參數放入map中,並返回null,如果鍵存在,則返回false,
  所以當鍵存不存在時為null,null==null為true,當鍵存在時,則返回false,這樣就做到了 相同數據的篩選
  putIfAbsent 源碼如下:
    

 

 

 

public static void main(String[] args) {
Person person1=new Person("1","張三","18","永遠18");
Person person2=new Person("1","張三","18","永遠18");
Person person3=new Person("1","張三","20","永遠18");
Person person4=new Person("1","張三","19","永遠18");
Person person5=new Person("1","張三","21","永遠18");
Person person6=new Person("1","張三","18","永遠18");
List<Person> personList=new ArrayList<>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
personList.add(person4);
personList.add(person5);
personList.add(person6);
List<Person> list=personList.stream().filter(distinctByKey(person -> person.getAge())).collect(Collectors.toList());
list.forEach(person -> System.out.println(person));

}
private static <T> Predicate<T> distinctByKey(Function<? super T,?> keyExtractor){
Map<Object,Boolean> map=new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)==null;
}
運行結果:
  

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM