Stream流與Lambda表達式(四) 自定義收集器

一、自定義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集合轉換為Set集合 存放相同元素
public class SetCustomCollector<T> implements Collector<T, Set<T>, Set<T>> {@Overridepublic Supplier<Set<T>> supplier() {System.out.println("supplier      invoked!");//  return TreeSet::new;return HashSet::new;}@Overridepublic BiConsumer<Set<T>, T> accumulator() {System.out.println("accumulator      invoked!");return Set<T>::add;}@Overridepublic BinaryOperator<Set<T>> combiner() {System.out.println("combiner      invoked!");return (first, last) -> {first.addAll(last);return first;};}@Overridepublic Function<Set<T>, Set<T>> finisher() {System.out.println("finisher      invoked!");return Function.identity();}@Overridepublic Set<Characteristics> characteristics() {System.out.println("characteristics      invoked!");return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH, Characteristics.UNORDERED));//  return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED));}}

二、自定義StudentCustomCollector收集器

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 陳楊*/// 將學生對象 按照HashMap<Integer,Student> 存放 sid student
public class StudentCustomCollector implements Collector<Student, List<Student>, Map<Integer, Student>> {@Overridepublic Supplier<List<Student>> supplier() {System.out.println("supplier      invoked!");return ArrayList::new;}@Overridepublic BiConsumer<List<Student>, Student> accumulator() {System.out.println("accumulator      invoked!");return (list, student) -> {System.out.println("accumulator:" + Thread.currentThread().getName());list.add(student);};}@Overridepublic BinaryOperator<List<Student>> combiner() {System.out.println("combiner      invoked!");return (first, last) -> {first.addAll(last);return first;};}@Overridepublic Function<List<Student>, Map<Integer, Student>> finisher() {System.out.println("finisher      invoked!");return list -> {Map<Integer, Student> map = new HashMap<>();list.forEach(student -> map.put(student.getId(), student));return map;};}@Overridepublic Set<Characteristics> characteristics() {System.out.println("Characteristics      invoked!");return Collections.unmodifiableSet(EnumSet.of(Characteristics.CONCURRENT));}//    Characteristics.IDENTITY_FINISH 從中間容器數據類型 轉換為 結果類型 數據類型一致//         若不一致 拋出類型轉換異常 finisher對中間容器數據-->結果類型 進行強制類型轉換//    Characteristics.CONCURRENT  多個線程同時操作同一個容器 --> 并行//          Indicates that this collector is <em>concurrent</em>, meaning that//          the result container can support the accumulator function being//          called concurrently with the same result container from multiple threads.//    parallelStream (多線程)并行流 操作 多個結果容器  -->  執行combiner//    Characteristics.CONCURRENT +  parallelStream  結果容器只有1個  ---> 不執行 combiner//    ConcurrentModificationException  并發修改異常//             注意:并行情況下 累加器對結果容器執行單一操作//                  不要在累加器返回的函數式接口實例中做額外的操作//                        不能打印集合類容 同時向集合里添加新元素//                          This exception may be thrown by methods that have detected concurrent//                          modification of an object when such modification is not permissible
}

三、SetCustomCollectorTest測試

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<Student> students;@Beforepublic void init() {students = new Students().init();}@Testpublic void testSetCustomCollector() {Set<Student> set = students.stream().collect(new SetCustomCollector<>());System.out.println(set);}/*public static <T, I> TerminalOp<T, I>makeRef(Collector<? super T, I, ?> collector) {Supplier<I> supplier = Objects.requireNonNull(collector).supplier();BiConsumer<I, ? super T> accumulator = collector.accumulator();BinaryOperator<I> combiner = collector.combiner();class ReducingSink extends Box<I>implements AccumulatingSink<T, I, ReducingSink> {@Overridepublic void begin(long size) {state = supplier.get();}@Overridepublic void accept(T t) {accumulator.accept(state, t);}@Overridepublic void combine(ReducingSink other) {state = combiner.apply(state, other.state);}}return new ReduceOp<T, I, ReducingSink>(StreamShape.REFERENCE) {@Overridepublic ReducingSink makeSink() {return new ReducingSink();}@Overridepublic int getOpFlags() {return collector.characteristics().contains(Collector.Characteristics.UNORDERED)? StreamOpFlag.NOT_ORDERED: 0;}};}*//*public final <R, A> 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<A, ? super P_OUT> 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);}*///    執行流程   方法調用順序//    container = evaluate(ReduceOps.makeRef(collector));//    Supplier<I> supplier = Objects.requireNonNull(collector).supplier();//    BiConsumer<I, ? super T> accumulator = collector.accumulator();//    BinaryOperator<I> combiner = collector.combiner();//    return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)是否有序//    return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)是否包含IDENTITY_FINISH//     ? (R) container  注意強制類型轉換  (中間類型 與 返回結果類型)//    注意強制類型轉換/*CollectorImpl(Supplier<A> supplier,BiConsumer<A, T> accumulator,BinaryOperator<A> combiner,Set<Characteristics> characteristics) {this(supplier, accumulator, combiner, castingIdentity(), characteristics);}@SuppressWarnings("unchecked")private static <I, R> Function<I, R> castingIdentity() {return i -> (R) i;}*///    EnumSet.of(Characteristics.IDENTITY_FINISH, Characteristics.UNORDERED)//    包含 IDENTITY_FINISH 打印結果//    supplier      invoked!//    accumulator      invoked!//    combiner      invoked!//    characteristics      invoked!//    characteristics      invoked!//    Set<Student>集合對象//    EnumSet.of(Characteristics.UNORDERED)//    不包含 IDENTITY_FINISH 打印結果//    supplier      invoked!//    accumulator      invoked!//    combiner      invoked!//    characteristics      invoked!//    characteristics      invoked!//    finisher      invoked!//    Set<Student>集合對象}

四、StudentCustomCollectorTest測試

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<Student> students;@Beforepublic void init() {students = new Students().init();}@Testpublic void testStudentCustomCollectorTest() {System.out.println("單線程");Map<Integer, Student> sequentialMap = students.stream().collect(new StudentCustomCollector());System.out.println("串行流執行效果:\n---------------------------------------\n"+sequentialMap);System.out.println("---------------------------------------\n");System.out.println("多線程");Map<Integer, Student> parallelMap = students.parallelStream().collect(new StudentCustomCollector());System.out.println("并行流執行效果:\n---------------------------------------\n"+parallelMap);System.out.println("---------------------------------------\n");}}

五、測試結果

 SetCustomCollectorTest測試結果.   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: 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:\IdeaProjects\design)
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測試.   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: 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:\IdeaProjects\design)
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!
串行流執行效果:
---------------------------------------
{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!
并行流執行效果:
---------------------------------------
{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)}
---------------------------------------

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/280248.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280248.shtml
英文地址,請注明出處:http://en.pswp.cn/news/280248.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ModelState.IsValid忽略型別的檢查錯誤

Web Api在Int或DateTime如果傳空值的話會自動幫忙設預設值&#xff0c;但是在ModelState.IsValid的時候&#xff0c;卻會出現型別上的錯誤.解決方式把Model改成正確&#xff0c;也就是預設允許可以為nullpublic class DemoModel { …

android 指紋添加_如何將手勢添加到Android手機的指紋掃描儀

android 指紋添加So you have a shiny new Android phone, equipped with a security-friendly fingerprint scanner. Congratulations! But did you know that, while useful on its own, you can actually make the fingerprint scanner do more than just unlock your phone…

關于前端性能優化

常用的優化有兩部分 第一&#xff1a;面向內容的優化 減少 HTTP 請求減少 DNS 查找避免重定向使用 Ajax 緩存延遲載入組件預先載入組件減少 DOM 元素數量切分組件到多個域最小化 iframe 的數量不要出現http 404 錯誤第二&#xff1a;面向 Server 縮小 Cookie針對 Web 組件使用域…

前端工程化:圍繞Jenkins打造工作流的過程

背景 1年前入職時&#xff0c;公司前端部門的靜態代碼部署都是用ftp工具拖拽部署&#xff0c;沒有記錄&#xff0c;沒有關聯&#xff0c;經常造成許多困擾的問題&#xff0c; 比如&#xff1a;今天有沒有其他人在我要部署的路徑上工作&#xff1f;我的代碼為啥被蓋掉了&#xf…

業務id轉密文短鏈的一種實現思路

業務場景&#xff1a; 買家通過電商app下單后&#xff0c;會受到一條短信&#xff0c;短信內容中包括改訂單詳情頁面的h5地址連接&#xff0c;因為是出現在短信中&#xff0c;所以對連接有要求&#xff1a;1.盡量短&#xff1b;2.安全性考慮&#xff0c;訂單在數據庫中對應的自…

百度高管:問心無愧

1月23日下午消息&#xff0c;今天下午&#xff0c;百度召開百家號2019內容創作者盛典&#xff0c;百度副總裁沈抖出席并發布演講。 就在前一天&#xff0c;一篇名為《搜索引擎百度已死》的文章刷屏&#xff0c;文中提到百度搜索有一半以上會指向百度自家產品&#xff0c;尤其百…

Vuex 學習筆記

Vuex 是什么&#xff1f; Vuex 是一個專為 Vue.js應用程序開發的狀態管理模式。由于SPA應用的模塊化&#xff0c;每個組件都有它各自的數據&#xff08;state&#xff09;、視圖&#xff08;view&#xff09;和方法&#xff08;actions&#xff09;&#xff0c;當項目內容越來越…

xdf文檔怎么轉換為pdf_如何將PDF文件和圖像轉換為Google文檔文檔

xdf文檔怎么轉換為pdfYou probably know you can create and edit documents with Google Docs, but you can edit more than just .doc files. Google Drive can also convert any PDF, JPG, PNG, or GIF into a document with fully editable text. Here’s how. 您可能知道可…

在現代 Windows 上使用經典 Windows 2000、XP、Vista 任務欄

你好&#xff0c;這里是 Dotnet 工具箱&#xff0c;定期分享 Dotnet 有趣&#xff0c;實用的工具和組件&#xff0c;希望對您有用&#xff01;前言您第一次使用的 Windows 是哪個版本的&#xff1f;我最早使用的 Windows XP&#xff0c;然后再經過 XP、7、8/8.1 、Windows 10&a…

oracle sys可以登錄,system權限不足,解決方法

今天在自己電腦上安裝了oracle 11g&#xff0c;安裝成功后發現 sys 可以正常登錄。system 無法登錄&#xff0c;顯示 ORA-01031: insufficient privileges(權限不足) select * from v$pwfile_users; 查看有sysdba權限的用戶 grant sysdba to system; 給system 授權sysdba權限…

airdroid黑屏_如何使用AirDroid從PC控制Android設備

airdroid黑屏AirDroid for Android replaces your USB cable for connecting to your PC. Transfer files back and forth, send text messages, play music, view your photos, and manage applications using a web browser or a desktop client. 適用于Android的AirDroid取代…

分析java程序

2019獨角獸企業重金招聘Python工程師標準>>> 最近公司的一個賬單推送的服務&#xff0c;發現有延遲。我排查的時候發現&#xff0c;有一個程序日志不動了&#xff08;采用消息隊列&#xff0c;部署了兩臺服務器來負載均衡&#xff09;。 網上說&#xff1a; jstack …

環境部署(九):linux下安裝python+chrome+Xvfb

在基于selenium進行的UI自動化測試中&#xff0c;開發調試環境一般都是windows操作系統。完成后需要部署到專門的測試環境。 如要要部署到linux環境的服務器&#xff08;阿里云、騰訊云&#xff09;執行&#xff0c;那么測試腳本也需要對應的瀏覽器支持&#xff0c; 才能正常進…

地理圍欄_什么是“地理圍欄”?

地理圍欄The term is popping up more frequently in news articles, appearing in product manuals, and highlighted as a feature in tons of mobile applications, but what exactly is geofencing? Read on as we explain what it is, why it’s appearing in more produ…

219. 單頁應用 會話管理(session、cookie、jwt)

原文鏈接&#xff1a;https://github.com/ly525/blog... 關鍵字&#xff1a;http-only, cookie,sessionid, vue-router, react-router, 安全&#xff0c;localStorage, jwt 需求描述 內部管理平臺&#xff0c;需要用戶登錄之后才能訪問。現在將 該平臺地址&#xff08;www.xxx.…

(原+譯)使用numpy.savez保存字典后讀取的問題

轉載請注明出處&#xff1a; http://www.cnblogs.com/darkknightzh/p/7608928.html 參考網址; https://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez python中&#xff0c;使用pickle保存變量時&#xff0c;如果變量過大&…

NLog 通過http保存日志

簡介NLog是一個基于.NET平臺編寫的類庫&#xff0c;我們可以使用NLog在應用程序中添加極為完善的跟蹤調試代碼。 NLog是一個簡單靈活的.NET日志記錄類庫。通過使用NLog&#xff0c;我們可以在任何一種.NET語言中輸出帶有上下文的&#xff08;contextual information&#xff09…

嵌套映射

1. 多對一嵌套查詢映射使用案例 package com.zixue.dao;import com.zixue.annotation.MyBatisRepository; import com.zixue.entity.Emp;/*** 員工表的DAO組件* */ MyBatisRepository public interface EmpDao {void save(Emp emp);Emp findById(int id);Emp findById2(int id)…

gopro dataset_如何將GoPro安裝到DSLR相機

gopro datasetIf you have a DSLR camera with a hot shoe, it’s easy to attach various flashes and other accessories right to your camera. But with a couple of cheap attachments on hand, you can mount your GoPro to your DSLR camera as well. 如果您的DSLR相機帶…

音頻 m4a 轉 wav

背景最近做智能家居&#xff0c;需要用到一些應答詞 需要自己錄制。但是在mac下面通過 QuickTime 錄制的是 m4a格式。但是應答詞需要 wav格式。所以就需要轉化了解決方法# sox 不行&#xff0c; ffmpeg 很麻煩&#xff0c;用 avconv 很簡單。安裝 如果沒有就安裝 # apt-get ins…