java8List集合根據對象的屬性去重


import static java.util.Comparator.comparingLong;

import static java.util.stream.Collectors.collectingAndThen;

import static java.util.stream.Collectors.toCollection;

// 根據id去重

     List<Person> unique = persons.stream().collect(

                collectingAndThen(

                        toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)

        );

分析:

collect是一個終端操作,它接收的參數是將流中的元素累積到匯總結果的各種方式(稱為收集器)

預定義收集器包括將流元素歸約和匯總到一個值.如下

工廠方法                返回類型                  

collectingAndThen   轉換函數返回的類型   包裹另一個轉換器,對其結果應用轉換函數

示例:Int count=Menu.getMenus.stream().collect(collectingAndThen(toList(),List::size))

 

toCollection            Collection<T>            把流中所有元素收集到給定的供應源創建的集合中

示例:ArrayList<Menu> menus=Menu.getMenus.stream().collect(Collectors.toCollection(ArrayList::new))

 

Comparator.comparing(Function keyExtractor)生成1Comparator對象,要求keyExtractor.apply()返回值一定要實現Comparable接口。從Student對象中提取id屬性,而idint類型(Integer實現了Comparable)comparingDouble()comparingLong()comparingInt()不過是comparing()更具體的版本,使用方式相同。如果是字符串比較用Comparator.comparing(Human::getName)


免責聲明!

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



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