资讯专栏INFORMATION COLUMN

Stream流与Lambda表达式(四) 自定义收集器

wind5o / 3431人阅读

摘要:一自定义收集器陈杨将集合转换为集合存放相同元素二自定义收集器陈杨将学生对象按照存放从中间容器数据类型转换为结果类型数据类型一致若不一致抛出类型转换异常对中间容器数据结果类型进行强制类型转换多个线程同时操作同一个容器并行多线

一、自定义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 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));
    }


}
二、自定义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 存放 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 从中间容器数据类型 转换为 结果类型 数据类型一致
    //         若不一致 抛出类型转换异常 finisher对中间容器数据-->结果类型 进行强制类型转换


    //    Characteristics.CONCURRENT  多个线程同时操作同一个容器 --> 并行
    //          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 (多线程)并行流 操作 多个结果容器  -->  执行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 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 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 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);
    }*/

    //    执行流程   方法调用顺序
    //    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  注意强制类型转换  (中间类型 与 返回结果类型)

    //    注意强制类型转换
    /*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 打印结果
    //    supplier      invoked!
    //    accumulator      invoked!
    //    combiner      invoked!
    //    characteristics      invoked!
    //    characteristics      invoked!
    //    Set集合对象


    //    EnumSet.of(Characteristics.UNORDERED)
    //    不包含 IDENTITY_FINISH 打印结果
    //    supplier      invoked!
    //    accumulator      invoked!
    //    combiner      invoked!
    //    characteristics      invoked!
    //    characteristics      invoked!
    //    finisher      invoked!
    //    Set集合对象


}
四、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 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("串行流执行效果:
---------------------------------------
"+sequentialMap);
        System.out.println("---------------------------------------
");

        System.out.println("多线程");
        Map parallelMap = students.parallelStream().collect(new StudentCustomCollector());
        System.out.println("并行流执行效果:
---------------------------------------
"+parallelMap);
        System.out.println("---------------------------------------
");
    }

}
五、测试结果
 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: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测试
 .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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!
串行流执行效果:
---------------------------------------
{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)}
---------------------------------------

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73347.html

相关文章

  • Stream流与Lambda达式(三) 静态工厂类Collectors

    摘要:陈杨一静态工厂类实现方式一静态工厂类实现方式静态工厂类最终由实现通过实现通过实现底层由实现是的一种具化表现形式使用拼接字符串二静态工厂类常用收集器二静态工厂类常用收集器返回一个不可修改的按照相遇的顺序返回一个不可修改的无序返回 /** * @author 陈杨 */ @SpringBootTest @RunWith(SpringRunner.class) public class...

    phodal 评论0 收藏0
  • Stream流与Lambda达式(二) Stream集器 Collector接口

    摘要:一收集器接口陈杨收集器接口汇聚操作的元素类型即流中元素类型汇聚操作的可变累积类型汇聚操作的结果类型接口一种可变汇聚操作将输入元素累积到可变结果容器中在处理完所有输入元素后可以选择将累积的结果转换为最终表示可选操作归约操作 一、Stream收集器 Collector接口 package com.java.design.java8.Stream; import com.java.desi...

    or0fun 评论0 收藏0
  • Stream流与Lambda达式(五) Stream BaseStream AutoClose

    摘要:陈杨一流的定义流支持串行并行聚合操作元素序列二流的创建流的创建以方法生成流三 package com.java.design.java8.Stream.StreamDetail; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframe...

    HitenDev 评论0 收藏0
  • Stream流与Lambda达式(六) SpliteratorDetail

    摘要:陈杨一流的创建源集合一流的创建源集合集合默认方法接口与静态类实现接口与静态类实现二接口二接口接口对数据源中元素进行遍历或分区延迟绑定数据源绑定时机首次遍历切分查询大小而不是在创建时非延迟绑定数据源绑定时机创建时或的方法首次调用与 package com.java.design.java8.Stream.StreamDetail.BaseStreamDetail; import or...

    cjie 评论0 收藏0
  • Java8新特性总览

    摘要:新特性总览标签本文主要介绍的新特性,包括表达式方法引用流默认方法组合式异步编程新的时间,等等各个方面。还有对应的和类型的函数连接字符串广义的归约汇总起始值,映射方法,二元结合二元结合。使用并行流时要注意避免共享可变状态。 Java8新特性总览 标签: java [TOC] 本文主要介绍 Java 8 的新特性,包括 Lambda 表达式、方法引用、流(Stream API)、默认方...

    mayaohua 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<