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);
    }
相关推荐
尘浮生4 分钟前
Java项目实战II基于微信小程序的电影院买票选座系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
hopetomorrow18 分钟前
学习路之PHP--使用GROUP BY 发生错误 SELECT list is not in GROUP BY clause .......... 解决
开发语言·学习·php
不是二师兄的八戒28 分钟前
本地 PHP 和 Java 开发环境 Docker 化与配置开机自启
java·docker·php
小牛itbull28 分钟前
ReactPress vs VuePress vs WordPress
开发语言·javascript·reactpress
请叫我欧皇i36 分钟前
html本地离线引入vant和vue2(详细步骤)
开发语言·前端·javascript
闲暇部落39 分钟前
‌Kotlin中的?.和!!主要区别
android·开发语言·kotlin
爱编程的小生39 分钟前
Easyexcel(2-文件读取)
java·excel
GIS瞧葩菜1 小时前
局部修改3dtiles子模型的位置。
开发语言·javascript·ecmascript
chnming19871 小时前
STL关联式容器之set
开发语言·c++
带多刺的玫瑰1 小时前
Leecode刷题C语言之统计不是特殊数字的数字数量
java·c语言·算法