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

匿名类:

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) {

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

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

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

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

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


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


        List 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 lambda表达式如何自定义一个toList Collector_第1张图片

Java lambda表达式如何自定义一个toList Collector_第2张图片

应用:

优化初始容器的容量:


/**
 *  – the type of input elements to the reduction operation
 *  – the mutable accumulation type of the reduction operation (often hidden as an implementation detail)
 *  – the result type of the reduction operation  最终返回结果的类型
 */
class ToListWithInitialCapacity implements Collector, List> {
    private int initialCapacity;

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

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

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

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

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


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

Jdk toList默认实现:

    /**
     * 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  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 
    Collector> toList() {
        return new CollectorImpl<>(ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }

Java lambda表达式如何自定义一个toList Collector_第3张图片

你可能感兴趣的:(java,开发语言)