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.mzph.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…