摘要:一收集器接口陳楊收集器接口匯聚操作的元素類型即流中元素類型匯聚操作的可變累積類型匯聚操作的結(jié)果類型接口一種可變匯聚操作將輸入元素累積到可變結(jié)果容器中在處理完所有輸入元素后可以選擇將累積的結(jié)果轉(zhuǎn)換為最終表示可選操作歸約操作
一、Stream收集器 Collector接口
package com.java.design.java8.Stream; import com.java.design.java8.entity.Student; import com.java.design.java8.entity.Students; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.*; import java.util.stream.Collectors; /** * @author 陳楊 */ @SpringBootTest @RunWith(SpringRunner.class) public class CollectorDetail { private List二、Collector 接口組成students; @Before public void init() { students=new Students().init(); } @Test public void testCollectorDetail() { // Collect 收集器 ---- Collector接口 // T-->匯聚操作的元素類型 即流中元素類型 // A-->匯聚操作的可變累積類型 // R-->匯聚操作的結(jié)果類型 // public interface Collector // Collector接口 一種可變匯聚操作 // 將輸入元素累積到可變結(jié)果容器中 // 在處理完所有輸入元素后 可以選擇將累積的結(jié)果轉(zhuǎn)換為最終表示(可選操作) // 歸約操作支持串行與并行 // A mutable reduction operation that accumulates input elements into a mutable result container, // optionally transforming the accumulated result into a final representation after all input elements // have been processed. Reduction operations can be performed either sequentially or in parallel. // Collectors 提供 Collector 匯聚實現(xiàn) 實際上是一個Collector工廠 // The class {@link Collectors} provides implementations of many common mutable reductions.
// Collector 由以下4個函數(shù)協(xié)同累積到容器 可選的執(zhí)行最終轉(zhuǎn)換 // supplier 創(chuàng)建一個新的結(jié)果容器 // accumulator累加器 將新數(shù)據(jù)元素合并到結(jié)果容器中 // combiner 合并結(jié)果容器 處理線程并發(fā) // finisher 對容器執(zhí)行可選的最終轉(zhuǎn)換 // // A {@code Collector} is specified by four functions that work together to // accumulate entries into a mutable result container, and optionally perform // a final transform on the result. They are: // creation of a new result container ({@link #supplier()}) // incorporating a new data element into a result container ({@link #accumulator()}) // combining two result containers into one ({@link #combiner()}) // performing an optional final transform on the container ({@link #finisher()})三、combiner
/* * A function that accepts two partial results and merges them. The * combiner function may fold state from one argument into the other and * return that, or may return a new result container. * * * BinaryOperator combiner(); */ /* supplier創(chuàng)建單個結(jié)果容器-->accumulator調(diào)用累積功能-->partition結(jié)果--分區(qū)容器-->combiner合并分區(qū)容器 A sequential implementation of a reduction using a collector would create a single result container using the supplier function, and invoke the accumulator function once for each input element. A parallel implementation would partition the input, create a result container for each partition, accumulate the contents of each partition into a subresult for that partition, and then use the combiner function to merge the subresults into a combined result. */四、identity associativity 約束
/* 確保串行與并行結(jié)果的一致性,滿足約束: identity associativity To ensure that sequential and parallel executions produce equivalent results, the collector functions must satisfy an identity and an associativity constraints. */ /* identity 約束: 對于任何部分累積的結(jié)果, 將其與空結(jié)果容器組合必須生成等效的結(jié)果 a == combiner.apply(a, supplier.get()) The identity constraint says that for any partially accumulated result, combining it with an empty result container must produce an equivalent result. That is, for a partially accumulated result {@code a} that is the result of any series of accumulator and combiner invocations, {@code a} must be equivalent to {@code combiner.apply(a, supplier.get())}. */ /* associativity 約束: 串行計算與并行拆分計算必須產(chǎn)生同等的結(jié)果 The associativity constraint says that splitting the computation must produce an equivalent result. That is, for any input elements {@code t1} and {@code t2}, the results {@code r1} and {@code r2} in the computation below must be equivalent: A a1 = supplier.get(); accumulator.accept(a1, t1); accumulator.accept(a1, t2); R r1 = finisher.apply(a1); // result without splitting A a2 = supplier.get(); accumulator.accept(a2, t1); A a3 = supplier.get(); accumulator.accept(a3, t2); R r2 = finisher.apply(combiner.apply(a2, a3)); // result with splitting */五、reduction 匯聚 的實現(xiàn)方式
// reduction 匯聚 的實現(xiàn)方式 // list.stream().reduce() 對象不可變 // list.stream().collect(Collectors.reducing()) 對象可變 // 單線程可以實現(xiàn)結(jié)果一致 但在多線程中就會出現(xiàn)錯誤 /* Libraries that implement reduction based on {@code Collector}, such as {@link Stream#collect(Collector)}, must adhere to the following constraints: 傳遞給accumulator的第一個參數(shù),傳遞給combiner的二個參數(shù),傳遞給finisher的參數(shù) 必須是函數(shù)(supplier accumulator combiner)上一次調(diào)用結(jié)果 理解: 參數(shù)類型A Supplier supplier(); BiConsumer accumulator(); BinaryOperator combiner(); Function finisher(); The first argument passed to the accumulator function, both arguments passed to the combiner function, and the argument passed to the finisher function must be the result of a previous invocation of the result supplier, accumulator, or combiner functions supplier accumulator combiner的實現(xiàn)結(jié)果--> 傳遞給下一次supplier accumulator combiner操作 或返還給匯聚操作的調(diào)用方 而不進(jìn)行其他操作 The implementation should not do anything with the result of any of the result supplier, accumulator, or combiner functions other than to pass them again to the accumulator, combiner, or finisher functions, or return them to the caller of the reduction operation 一個結(jié)果傳遞給combiner finisher而相同的對象沒有從此函數(shù)中返回 這個結(jié)果不會再被使用 這個傳入結(jié)果是被消費(fèi)了 生成了新的對象 If a result is passed to the combiner or finisher function, and the same object is not returned from that function, it is never used again 一旦結(jié)果傳遞給combiner finisher 則不再會傳遞給accumulator 說明流中元素已經(jīng)傳遞完全 accumulator任務(wù)已執(zhí)行完畢 Once a result is passed to the combiner or finisher function, it is never passed to the accumulator function again 非并發(fā)單線程 For non-concurrent collectors, any result returned from the result supplier, accumulator, or combiner functions must be serially thread-confined. This enables collection to occur in parallel without the {@code Collector} needing to implement any additional synchronization. The reduction implementation must manage that the input is properly partitioned, that partitions are processed in isolation, and combining happens only after accumulation is complete 并發(fā)多線程 For concurrent collectors, an implementation is free to (but not required to) implement reduction concurrently. A concurrent reduction is one where the accumulator function is called concurrently from multiple threads, using the same concurrently-modifiable result container, rather than keeping the result isolated during accumulation. A concurrent reduction should only be applied if the collector has the {@link Characteristics#UNORDERED} characteristics or if the originating data is unordered */六、Characteristics對Collectors的性能優(yōu)化
/* Characteristics對Collectors的性能優(yōu)化 * * Collectors also have a set of characteristics, that provide hints that can be used by a * reduction implementation to provide better performance. * * * Characteristics indicating properties of a {@code Collector}, which can * be used to optimize reduction implementations. * * enum Characteristics { * * Indicates that this collector is concurrent, meaning that * the result container can support the accumulator function being * called concurrently with the same result container from multiple * threads. * * If a {@code CONCURRENT} collector is not also {@code UNORDERED}, * then it should only be evaluated concurrently if applied to an * unordered data source. CONCURRENT, 多線程處理并發(fā) 一定要保證線程安全 使用無序數(shù)據(jù)源 與UNORDERED聯(lián)合使用 * Indicates that the collection operation does not commit to preserving * the encounter order of input elements. (This might be true if the * result container has no intrinsic order, such as a {@link Set}.) UNORDERED, 無序集合 * Indicates that the finisher function is the identity function and * can be elided. If set, it must be the case that an unchecked cast * from A to R will succeed. IDENTITY_FINISH 強(qiáng)制類型轉(zhuǎn)換 }*/七、Collector接口與 Collectors
// Collectors---> Collector接口簡單實現(xiàn) 靜態(tài)內(nèi)部類CollectorImpl // 為什么要在Collectors類內(nèi)部定義一個靜態(tài)內(nèi)部類CollectorImpl: // Collectors是一個工廠、輔助類 方法的定義是靜態(tài)的 // 以類名直接調(diào)用方法的方式向developer提供最常見的Collector實現(xiàn) 其實現(xiàn)方式是CollectorImpl // CollectorImpl類 有且僅有在 Collectors類 中使用 所以放在一起八、測試方法:
// Accumulate names into a List 將學(xué)生姓名累積成ArrayList集合 List九、測試結(jié)果snameList = students.stream() .map(Student::getName).collect(Collectors.toList()); System.out.println("將學(xué)生姓名累積成ArrayList集合:" + snameList.getClass()); System.out.println(snameList); System.out.println("----------------------------------------- "); // Accumulate names into a TreeSet 將學(xué)生姓名累積成TreeSet集合 Set snameTree = students.stream() .map(Student::getName).collect(Collectors.toCollection(TreeSet::new)); System.out.println("將學(xué)生姓名累積成TreeSet集合:" + snameTree.getClass()); System.out.println(snameTree); System.out.println("----------------------------------------- "); // Convert elements to strings and concatenate them, separated by commas 將學(xué)生姓名累積成一個Json串 以逗號分隔 String joinedStudents = students.stream() .map(Student::toString).collect(Collectors.joining(",")); System.out.println(" 將學(xué)生姓名累積成一個Json串 以逗號分隔:" + joinedStudents); System.out.println("----------------------------------------- "); // Compute sum of salaries of students 求學(xué)生總薪水 double totalSalary = students.stream() .mapToDouble(Student::getSalary).sum(); System.out.println("學(xué)生總薪水:" + totalSalary); System.out.println("----------------------------------------- "); // the min id of students 打印最小id的學(xué)生信息 System.out.println("最小id的學(xué)生信息:"); students.stream() .min(Comparator.comparingInt(Student::getId)) .ifPresent(System.out::println); System.out.println("----------------------------------------- "); // the max id of students 打印最大id的學(xué)生信息 System.out.println("最大id的學(xué)生信息:"); students.stream() .max(Comparator.comparingInt(Student::getId)) .ifPresent(System.out::println); System.out.println("----------------------------------------- "); // Compute avg of Age of students 求學(xué)生平均年齡 Double avgAge = students.stream() .collect(Collectors.averagingInt(Student::getAge)); System.out.println("學(xué)生平均年齡:" + avgAge); System.out.println("----------------------------------------- "); // Compute SummaryStatistics of Age of students 打印學(xué)生年齡的匯總信息 IntSummaryStatistics ageSummaryStatistics = students.stream() .collect(Collectors.summarizingInt(Student::getAge)); System.out.println("學(xué)生年齡的匯總信息:" + ageSummaryStatistics); System.out.println("----------------------------------------- "); // 根據(jù)性別分組 取id最小的學(xué)生 // 直接使用Collectors.minBy返回的是Optional // 因能確認(rèn)不為Null 使用Collectors.collectingAndThen-->Optional::get獲取 Map minIdStudent = students.stream(). collect(Collectors.groupingBy(Student::getSex, Collectors.collectingAndThen (Collectors.minBy(Comparator.comparingInt(Student::getId)), Optional::get))); System.out.println(minIdStudent); System.out.println("----------------------------------------- "); } }
. ____ _ __ _ _ / / ___"_ __ _ _(_)_ __ __ _ ( ( )\___ | "_ | "_| | "_ / _` | / ___)| |_)| | | | | || (_| | ) ) ) ) " |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.2.RELEASE) 2019-02-20 16:11:56.217 INFO 17260 --- [ main] c.j.design.java8.Stream.CollectorDetail : Starting CollectorDetail on DESKTOP-87RMBG4 with PID 17260 (started by 46250 in E:IdeaProjectsdesign) 2019-02-20 16:11:56.223 INFO 17260 --- [ main] c.j.design.java8.Stream.CollectorDetail : No active profile set, falling back to default profiles: default 2019-02-20 16:11:56.699 INFO 17260 --- [ main] c.j.design.java8.Stream.CollectorDetail : Started CollectorDetail in 0.678 seconds (JVM running for 1.401) ----------------------------------------- 將學(xué)生姓名累積成ArrayList集合:class java.util.ArrayList [Kirito, Asuna, Sinon, Yuuki, Alice] ----------------------------------------- 將學(xué)生姓名累積成TreeSet集合:class java.util.TreeSet [Alice, Asuna, Kirito, Sinon, Yuuki] ----------------------------------------- 將學(xué)生姓名累積成一個Json串 以逗號分隔:Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8),Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8),Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8),Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8),Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8) ----------------------------------------- 學(xué)生總薪水:4.999999995E9 ----------------------------------------- 最小id的學(xué)生信息: Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8) ----------------------------------------- 最大id的學(xué)生信息: Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8) ----------------------------------------- 學(xué)生平均年齡:16.0 ----------------------------------------- 學(xué)生年齡的匯總信息:IntSummaryStatistics{count=5, sum=80, min=14, average=16.000000, max=18} ----------------------------------------- {Female=Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8), Male=Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)} -----------------------------------------
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/73352.html
摘要:一自定義收集器陳楊將集合轉(zhuǎn)換為集合存放相同元素二自定義收集器陳楊將學(xué)生對象按照存放從中間容器數(shù)據(jù)類型轉(zhuǎn)換為結(jié)果類型數(shù)據(jù)類型一致若不一致拋出類型轉(zhuǎn)換異常對中間容器數(shù)據(jù)結(jié)果類型進(jìn)行強(qiáng)制類型轉(zhuǎn)換多個線程同時操作同一個容器并行多線 一、自定義SetCustomCollector收集器 package com.java.design.Stream.CustomCollector; impor...
摘要:陳楊一靜態(tài)工廠類實現(xiàn)方式一靜態(tài)工廠類實現(xiàn)方式靜態(tài)工廠類最終由實現(xiàn)通過實現(xiàn)通過實現(xiàn)底層由實現(xiàn)是的一種具化表現(xiàn)形式使用拼接字符串二靜態(tài)工廠類常用收集器二靜態(tài)工廠類常用收集器返回一個不可修改的按照相遇的順序返回一個不可修改的無序返回 /** * @author 陳楊 */ @SpringBootTest @RunWith(SpringRunner.class) public class...
摘要:新特性總覽標(biāo)簽本文主要介紹的新特性,包括表達(dá)式方法引用流默認(rèn)方法組合式異步編程新的時間,等等各個方面。還有對應(yīng)的和類型的函數(shù)連接字符串廣義的歸約匯總起始值,映射方法,二元結(jié)合二元結(jié)合。使用并行流時要注意避免共享可變狀態(tài)。 Java8新特性總覽 標(biāo)簽: java [TOC] 本文主要介紹 Java 8 的新特性,包括 Lambda 表達(dá)式、方法引用、流(Stream API)、默認(rèn)方...
摘要:一流轉(zhuǎn)換為數(shù)組集合陳楊將流轉(zhuǎn)換為數(shù)組將流轉(zhuǎn)換為數(shù)組將流轉(zhuǎn)換為集合將流轉(zhuǎn)換為集合解析 一、流 轉(zhuǎn)換為數(shù)組、集合 package com.java.design.java8.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context...
摘要:收集器用作高級歸約剛剛的結(jié)論又引出了優(yōu)秀的函數(shù)式設(shè)計的另一個好處更易復(fù)合和重用。更具體地說,對流調(diào)用方法將對流中的元素觸發(fā)一個歸約操作由來參數(shù)化。另一個常見的返回單個值的歸約操作是對流中對象的一個數(shù)值字段求和。 用流收集數(shù)據(jù) 我們在前一章中學(xué)到,流可以用類似于數(shù)據(jù)庫的操作幫助你處理集合。你可以把Java 8的流看作花哨又懶惰的數(shù)據(jù)集迭代器。它們支持兩種類型的操作:中間操作(如 filt...
閱讀 1953·2021-10-12 10:12
閱讀 3083·2019-08-30 15:44
閱讀 851·2019-08-30 15:43
閱讀 3001·2019-08-30 14:02
閱讀 2086·2019-08-30 12:54
閱讀 3508·2019-08-26 17:05
閱讀 1993·2019-08-26 13:34
閱讀 1061·2019-08-26 11:54