Java lambda表达式如何自定义一个toList Collector

匿名类:

java 复制代码
package l8;

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;
import java.util.stream.Collectors;

public class CollectorToList2 {
    public static void main(String[] args) {

        /**
         *
         <T> -- the type of input elements to the reduction operation
         <A> -- the mutable accumulation type of the reduction operation (often hidden as an implementation detail)
         <R> -- the result type of the reduction operation  最终返回结果的类型
         */
        Collector<Integer, List<Integer>, List<String>> toList = new Collector<Integer, List<Integer>, List<String>>() {

            // 初始一个容器,用于做为累加的容器
            @Override
            public Supplier<List<Integer>> supplier() {
                return () -> new ArrayList<>();
            }

            /**
             * 元素累加
             * @return
             */
            @Override
            public BiConsumer<List<Integer>, Integer> accumulator() {
                return List::add;
            }

            /**
             * 将多个容器进行合并(应该是在并行Stream时使用的)
             * @return
             */
            @Override
            public BinaryOperator<List<Integer>> combiner() {
                return (a, b) -> {
                    System.out.println("combiner call");
                    a.addAll(b);
                    return a;
                };
            }

            /**
             * 最终类型转换
             * @return
             */
            @Override
            public Function<List<Integer>, List<String>> finisher() {
                return list -> list.stream()
                        .map(e -> e + "").collect(Collectors.toList());
            }


            @Override
            public Set<Characteristics> characteristics() {
                return Collections.singleton(Characteristics.UNORDERED);
            }
        };


        List<String> collect = Arrays.asList(1, 2, 3).stream().collect(toList);
        System.out.println(collect);

        collect = Arrays.asList(1, 2, 3).parallelStream().collect(toList);
        System.out.println(collect);
    }
}
javascript:void(0)

Combiner:

应用:

优化初始容器的容量:

java 复制代码
/**
 * <T> -- the type of input elements to the reduction operation
 * <A> -- the mutable accumulation type of the reduction operation (often hidden as an implementation detail)
 * <R> -- the result type of the reduction operation  最终返回结果的类型
 */
class ToListWithInitialCapacity implements Collector<Integer, List<Integer>, List<String>> {
    private int initialCapacity;

    public ToListWithInitialCapacity(int initialCapacity) {
        this.initialCapacity = initialCapacity;
    }

    // 初始一个容器,用于做为累加的容器
    @Override
    public Supplier<List<Integer>> supplier() {
        return () -> new ArrayList<>(initialCapacity);
    }

    /**
     * 元素累加
     *
     * @return
     */
    @Override
    public BiConsumer<List<Integer>, Integer> accumulator() {
        return List::add;
    }

    /**
     * 将多个容器进行合并(应该是在并行Stream时使用的)
     *
     * @return
     */
    @Override
    public BinaryOperator<List<Integer>> combiner() {
        return (a, b) -> {
            System.out.println("combiner call");
            a.addAll(b);
            return a;
        };
    }

    /**
     * 最终类型转换
     *
     * @return
     */
    @Override
    public Function<List<Integer>, List<String>> finisher() {
        return list -> list.stream()
                .map(e -> e + "").collect(Collectors.toList());
    }


    @Override
    public Set<Characteristics> characteristics() {
        return Collections.singleton(Characteristics.UNORDERED);
    }
}

Jdk toList默认实现:

java 复制代码
    /**
     * Returns a {@code Collector} that accumulates the input elements into a
     * new {@code List}. There are no guarantees on the type, mutability,
     * serializability, or thread-safety of the {@code List} returned; if more
     * control over the returned {@code List} is required, use {@link #toCollection(Supplier)}.
     *
     * @param <T> the type of the input elements
     * @return a {@code Collector} which collects all the input elements into a
     * {@code List}, in encounter order
     */
    public static <T>
    Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>(ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }
相关推荐
通信仿真实验室26 分钟前
(10)MATLAB莱斯(Rician)衰落信道仿真1
开发语言·matlab
勿语&29 分钟前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
ok!ko3 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
2402_857589364 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰4 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer4 小时前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
IT良4 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
哎呦没5 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
Kalika0-05 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch5 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j