摘要:一自定義收集器陳楊將集合轉(zhuǎn)換為集合存放相同元素二自定義收集器陳楊將學(xué)生對(duì)象按照存放從中間容器數(shù)據(jù)類型轉(zhuǎn)換為結(jié)果類型數(shù)據(jù)類型一致若不一致拋出類型轉(zhuǎn)換異常對(duì)中間容器數(shù)據(jù)結(jié)果類型進(jìn)行強(qiáng)制類型轉(zhuǎn)換多個(gè)線程同時(shí)操作同一個(gè)容器并行多線
一、自定義SetCustomCollector收集器
package com.java.design.Stream.CustomCollector; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; /** * @author 陳楊 */ // 將List集合轉(zhuǎn)換為Set集合 存放相同元素 public class SetCustomCollector二、自定義StudentCustomCollector收集器implements Collector , Set > { @Override public Supplier > supplier() { System.out.println("supplier invoked!"); // return TreeSet::new; return HashSet::new; } @Override public BiConsumer , T> accumulator() { System.out.println("accumulator invoked!"); return Set ::add; } @Override public BinaryOperator > combiner() { System.out.println("combiner invoked!"); return (first, last) -> { first.addAll(last); return first; }; } @Override public Function , Set > finisher() { System.out.println("finisher invoked!"); return Function.identity(); } @Override public Set characteristics() { System.out.println("characteristics invoked!"); return Collections.unmodifiableSet(EnumSet.of (Characteristics.IDENTITY_FINISH, Characteristics.UNORDERED)); // return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED)); } }
package com.java.design.Stream.CustomCollector; import com.java.design.java8.entity.Student; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; /** * @author 陳楊 */ // 將學(xué)生對(duì)象 按照HashMap三、SetCustomCollectorTest測(cè)試存放 sid student public class StudentCustomCollector implements Collector , Map > { @Override public Supplier > supplier() { System.out.println("supplier invoked!"); return ArrayList::new; } @Override public BiConsumer
, Student> accumulator() { System.out.println("accumulator invoked!"); return (list, student) -> { System.out.println("accumulator:" + Thread.currentThread().getName()); list.add(student); }; } @Override public BinaryOperator
> combiner() { System.out.println("combiner invoked!"); return (first, last) -> { first.addAll(last); return first; }; } @Override public Function
, Map
> finisher() { System.out.println("finisher invoked!"); return list -> { Map map = new HashMap<>(); list.forEach(student -> map.put(student.getId(), student)); return map; }; } @Override public Set characteristics() { System.out.println("Characteristics invoked!"); return Collections.unmodifiableSet(EnumSet.of(Characteristics.CONCURRENT)); } // Characteristics.IDENTITY_FINISH 從中間容器數(shù)據(jù)類型 轉(zhuǎn)換為 結(jié)果類型 數(shù)據(jù)類型一致 // 若不一致 拋出類型轉(zhuǎn)換異常 finisher對(duì)中間容器數(shù)據(jù)-->結(jié)果類型 進(jìn)行強(qiáng)制類型轉(zhuǎn)換 // Characteristics.CONCURRENT 多個(gè)線程同時(shí)操作同一個(gè)容器 --> 并行 // 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. // parallelStream (多線程)并行流 操作 多個(gè)結(jié)果容器 --> 執(zhí)行combiner // Characteristics.CONCURRENT + parallelStream 結(jié)果容器只有1個(gè) ---> 不執(zhí)行 combiner // ConcurrentModificationException 并發(fā)修改異常 // 注意:并行情況下 累加器對(duì)結(jié)果容器執(zhí)行單一操作 // 不要在累加器返回的函數(shù)式接口實(shí)例中做額外的操作 // 不能打印集合類容 同時(shí)向集合里添加新元素 // This exception may be thrown by methods that have detected concurrent // modification of an object when such modification is not permissible }
package com.java.design.java8.Stream.CustomCollector; import com.java.design.Stream.CustomCollector.SetCustomCollector; 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.List; import java.util.Set; /** * @author 陳楊 */ @SpringBootTest @RunWith(SpringRunner.class) public class SetCustomCollectorTest { private List四、StudentCustomCollectorTest測(cè)試students; @Before public void init() { students = new Students().init(); } @Test public void testSetCustomCollector() { Set set = students.stream().collect(new SetCustomCollector<>()); System.out.println(set); } /*public static TerminalOp makeRef(Collector super T, I, ?> collector) { Supplier supplier = Objects.requireNonNull(collector).supplier(); BiConsumer accumulator = collector.accumulator(); BinaryOperator combiner = collector.combiner(); class ReducingSink extends Box implements AccumulatingSink { @Override public void begin(long size) { state = supplier.get(); } @Override public void accept(T t) { accumulator.accept(state, t); } @Override public void combine(ReducingSink other) { state = combiner.apply(state, other.state); } } return new ReduceOp (StreamShape.REFERENCE) { @Override public ReducingSink makeSink() { return new ReducingSink(); } @Override public int getOpFlags() { return collector.characteristics().contains(Collector.Characteristics.UNORDERED) ? StreamOpFlag.NOT_ORDERED : 0; } }; }*/ /*public final R collect(Collector super P_OUT, A, R> collector) { A container; if (isParallel() && (collector.characteristics().contains(Collector.Characteristics.CONCURRENT)) && (!isOrdered() || collector.characteristics().contains(Collector.Characteristics.UNORDERED))) { container = collector.supplier().get(); BiConsumer accumulator = collector.accumulator(); forEach(u -> accumulator.accept(container, u)); } else { container = evaluate(ReduceOps.makeRef(collector)); } return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH) ? (R) container : collector.finisher().apply(container); }*/ // 執(zhí)行流程 方法調(diào)用順序 // container = evaluate(ReduceOps.makeRef(collector)); // Supplier supplier = Objects.requireNonNull(collector).supplier(); // BiConsumer accumulator = collector.accumulator(); // BinaryOperator combiner = collector.combiner(); // return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)是否有序 // return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)是否包含IDENTITY_FINISH // ? (R) container 注意強(qiáng)制類型轉(zhuǎn)換 (中間類型 與 返回結(jié)果類型) // 注意強(qiáng)制類型轉(zhuǎn)換 /*CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Set characteristics) { this(supplier, accumulator, combiner, castingIdentity(), characteristics); } @SuppressWarnings("unchecked") private static Function castingIdentity() { return i -> (R) i; }*/ // EnumSet.of(Characteristics.IDENTITY_FINISH, Characteristics.UNORDERED) // 包含 IDENTITY_FINISH 打印結(jié)果 // supplier invoked! // accumulator invoked! // combiner invoked! // characteristics invoked! // characteristics invoked! // Set 集合對(duì)象 // EnumSet.of(Characteristics.UNORDERED) // 不包含 IDENTITY_FINISH 打印結(jié)果 // supplier invoked! // accumulator invoked! // combiner invoked! // characteristics invoked! // characteristics invoked! // finisher invoked! // Set 集合對(duì)象 }
package com.java.design.java8.Stream.CustomCollector; import com.java.design.Stream.CustomCollector.StudentCustomCollector; 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.List; import java.util.Map; /** * @author 陳楊 */ @SpringBootTest @RunWith(SpringRunner.class) public class StudentCustomCollectorTest { private List五、測(cè)試結(jié)果students; @Before public void init() { students = new Students().init(); } @Test public void testStudentCustomCollectorTest() { System.out.println("單線程"); Map sequentialMap = students.stream().collect(new StudentCustomCollector()); System.out.println("串行流執(zhí)行效果: --------------------------------------- "+sequentialMap); System.out.println("--------------------------------------- "); System.out.println("多線程"); Map parallelMap = students.parallelStream().collect(new StudentCustomCollector()); System.out.println("并行流執(zhí)行效果: --------------------------------------- "+parallelMap); System.out.println("--------------------------------------- "); } }
SetCustomCollectorTest測(cè)試結(jié)果 . ____ _ __ _ _ / / ___"_ __ _ _(_)_ __ __ _ ( ( )\___ | "_ | "_| | "_ / _` | / ___)| |_)| | | | | || (_| | ) ) ) ) " |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.2.RELEASE) 2019-02-20 17:14:45.547 INFO 3260 --- [ main] c.j.d.j.S.C.SetCustomCollectorTest : Starting SetCustomCollectorTest on DESKTOP-87RMBG4 with PID 3260 (started by 46250 in E:IdeaProjectsdesign) 2019-02-20 17:14:45.548 INFO 3260 --- [ main] c.j.d.j.S.C.SetCustomCollectorTest : No active profile set, falling back to default profiles: default 2019-02-20 17:14:46.055 INFO 3260 --- [ main] c.j.d.j.S.C.SetCustomCollectorTest : Started SetCustomCollectorTest in 0.686 seconds (JVM running for 1.43) supplier invoked! accumulator invoked! combiner invoked! characteristics invoked! characteristics invoked! [Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8), Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8), Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8), Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8), Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8)]
StudentCustomCollectorTest測(cè)試 . ____ _ __ _ _ / / ___"_ __ _ _(_)_ __ __ _ ( ( )\___ | "_ | "_| | "_ / _` | / ___)| |_)| | | | | || (_| | ) ) ) ) " |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.2.RELEASE) 2019-02-20 17:15:52.817 INFO 3292 --- [ main] c.j.d.j.S.C.StudentCustomCollectorTest : Starting StudentCustomCollectorTest on DESKTOP-87RMBG4 with PID 3292 (started by 46250 in E:IdeaProjectsdesign) 2019-02-20 17:15:52.818 INFO 3292 --- [ main] c.j.d.j.S.C.StudentCustomCollectorTest : No active profile set, falling back to default profiles: default 2019-02-20 17:15:53.354 INFO 3292 --- [ main] c.j.d.j.S.C.StudentCustomCollectorTest : Started StudentCustomCollectorTest in 0.745 seconds (JVM running for 1.439) 單線程 supplier invoked! accumulator invoked! combiner invoked! Characteristics invoked! accumulator:main accumulator:main accumulator:main accumulator:main accumulator:main Characteristics invoked! finisher invoked! 串行流執(zhí)行效果: --------------------------------------- {1=Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8), 2=Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8), 3=Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8), 4=Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8), 5=Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)} --------------------------------------- 多線程 Characteristics invoked! Characteristics invoked! supplier invoked! accumulator invoked! combiner invoked! Characteristics invoked! accumulator:main accumulator:ForkJoinPool.commonPool-worker-5 accumulator:ForkJoinPool.commonPool-worker-5 accumulator:ForkJoinPool.commonPool-worker-3 accumulator:main Characteristics invoked! finisher invoked! 并行流執(zhí)行效果: --------------------------------------- {1=Student(id=1, name=Kirito, sex=Male, age=18, addr=Sword Art Online, salary=9.99999999E8), 2=Student(id=2, name=Asuna, sex=Female, age=17, addr=Sword Art Online, salary=9.99999999E8), 3=Student(id=3, name=Sinon, sex=Female, age=16, addr=Gun Gale Online, salary=9.99999999E8), 4=Student(id=4, name=Yuuki, sex=Female, age=15, addr=Alfheim Online, salary=9.99999999E8), 5=Student(id=5, name=Alice, sex=Female, age=14, addr=Alicization, salary=9.99999999E8)} ---------------------------------------
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/73347.html
摘要:陳楊一靜態(tài)工廠類實(shí)現(xiàn)方式一靜態(tài)工廠類實(shí)現(xiàn)方式靜態(tài)工廠類最終由實(shí)現(xiàn)通過實(shí)現(xiàn)通過實(shí)現(xiàn)底層由實(shí)現(xiàn)是的一種具化表現(xiàn)形式使用拼接字符串二靜態(tài)工廠類常用收集器二靜態(tài)工廠類常用收集器返回一個(gè)不可修改的按照相遇的順序返回一個(gè)不可修改的無(wú)序返回 /** * @author 陳楊 */ @SpringBootTest @RunWith(SpringRunner.class) public class...
摘要:一收集器接口陳楊收集器接口匯聚操作的元素類型即流中元素類型匯聚操作的可變累積類型匯聚操作的結(jié)果類型接口一種可變匯聚操作將輸入元素累積到可變結(jié)果容器中在處理完所有輸入元素后可以選擇將累積的結(jié)果轉(zhuǎn)換為最終表示可選操作歸約操作 一、Stream收集器 Collector接口 package com.java.design.java8.Stream; import com.java.desi...
摘要:陳楊一流的定義流支持串行并行聚合操作元素序列二流的創(chuàng)建流的創(chuàng)建以方法生成流三 package com.java.design.java8.Stream.StreamDetail; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframe...
摘要:陳楊一流的創(chuàng)建源集合一流的創(chuàng)建源集合集合默認(rèn)方法接口與靜態(tài)類實(shí)現(xiàn)接口與靜態(tài)類實(shí)現(xiàn)二接口二接口接口對(duì)數(shù)據(jù)源中元素進(jìn)行遍歷或分區(qū)延遲綁定數(shù)據(jù)源綁定時(shí)機(jī)首次遍歷切分查詢大小而不是在創(chuàng)建時(shí)非延遲綁定數(shù)據(jù)源綁定時(shí)機(jī)創(chuàng)建時(shí)或的方法首次調(diào)用與 package com.java.design.java8.Stream.StreamDetail.BaseStreamDetail; import or...
摘要:新特性總覽標(biāo)簽本文主要介紹的新特性,包括表達(dá)式方法引用流默認(rèn)方法組合式異步編程新的時(shí)間,等等各個(gè)方面。還有對(duì)應(yīng)的和類型的函數(shù)連接字符串廣義的歸約匯總起始值,映射方法,二元結(jié)合二元結(jié)合。使用并行流時(shí)要注意避免共享可變狀態(tài)。 Java8新特性總覽 標(biāo)簽: java [TOC] 本文主要介紹 Java 8 的新特性,包括 Lambda 表達(dá)式、方法引用、流(Stream API)、默認(rèn)方...
閱讀 3949·2021-11-22 13:53
閱讀 1676·2021-08-25 09:39
閱讀 2410·2019-08-29 18:36
閱讀 1469·2019-08-26 13:35
閱讀 1215·2019-08-26 11:57
閱讀 1678·2019-08-23 15:57
閱讀 803·2019-08-23 14:55
閱讀 1163·2019-08-23 14:51