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,一经查实,立即删除!

相关文章

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…

百度高管:问心无愧

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…

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…

嵌套映射

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相机带…

jQuery已经过时了,还需要学吗?

说起jQuery&#xff0c;很多刚参加工作的程序员都没用过&#xff0c;甚至没听过。曾几何时jQuery可是秒杀一切Js库&#xff0c;大有一统江山的情况&#xff0c;可是在顶峰的时候&#xff0c;瞬间被Vue、React、Angela三大框架斩于马下。从百度指数&#xff0c;我们也看出在2015…

Bootstrap01

Bootstrap01内容概要 一.使用Bootstrap的步骤 1.下载Bootstrap类库,包含三个部分,fonts,css,Bootstrap 2.导入项目中,在头部引入JQ,css和Bootstrap 注意:JQ要引入在Bootstrap前面! 3.使用css样式时,全部使用class属性 二.全局CSS概要 1.仅支持H5文档格式 2.移动设备优先,需要在…

ios raise_如何在iOS 10中关闭“ Raise to Wake”

ios raiseRaise to Wake is a new Lock screen feature available in iOS 10. It allows you to wake your phone’s screen simply by picking up your phone. This feature is on by default, but if you’d rather not use it, it’s simple to turn off. “唤醒”是iOS 10中…

资源调度器调研

2019独角兽企业重金招聘Python工程师标准>>> 场景描述&#xff1a; 异步触发和Crontab触发 YARN(Yet Another Resource Negotiator)Hadoop 资源管理器 主要构成&#xff1a; RM(ResourceManager)是一个全局的资源管理器&#xff0c;负责整个系统的资源管理和分配。…

WPF-19 IValueConverter接口

我们先来看看微软官方给出的定语&#xff1a;提供将自定义逻辑应用于绑定的方法&#xff0c;我们来看一下该接口的定义&#xff0c;Convert提供了将数据源到UI的格式化&#xff0c;ConvertBack表示反向namespace System.Windows.Data {//// Summary:// Provides a way to a…

使用 Azure CLI 将 IaaS 资源从经典部署模型迁移到 Azure Resource Manager 部署模型

以下步骤演示如何使用 Azure 命令行接口 (CLI) 命令将基础结构即服务 (IaaS) 资源从经典部署模型迁移到 Azure Resource Manager 部署模型。 本文中的操作需要 Azure CLI。 Note 此处描述的所有操作都是幂等的。 如果你遇到功能不受支持或配置错误以外的问题&#xff0c;建议你…

黑苹果不能imessage_如何修复iMessage在iOS 10中不显示消息效果

黑苹果不能imessageiMessage got a huge update in iOS 10, adding things like third-party app integration, rich links, and a number of fun graphical effects for messages. If you’re seeing messages that say something like “(sent with Invisible Ink)” instead…

从技术总监到开源社区运营:过去两年,我都做了点啥?

这是头哥侃码的第267篇原创今天&#xff0c;这是我离开前公司的第 7 天。相信有不少吃瓜群众都很好奇&#xff0c;你这些天都在干啥&#xff1f;是不是蓬莱乐逍遥&#xff0c;过上了那悠闲的神仙日子&#xff1f;还是趁着疫情管控逐渐放开&#xff0c;和家人一起去深山老林里吸…

查看模拟器使用端口_为什么我们仍然使用模拟音频端口?

查看模拟器使用端口When leaks about what the chassis of the iPhone 7 might look like hit headlines earlier this week, technology columnists and industry analysts jumped on the chance to report that Apple’s next device may finally ditch its 3.5mm audio port…