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