Java 8 stream 中重要的Collector接口

接口Collector < T, A, R >:

T is the generic type of the items in the stream to be collected.
A is the type of the accumulator, the object on which the partial result will be accumulated during the collection process.
R is the type of the object (typically, but not always, the collection) resulting from the collect operation.

T 是要收集的流中的项的泛型类型。
A 是累加器的类型, 在收集过程中将在其上累积部分结果的对象。
R 是收集操作产生的对象 (通常但不总是集合) 的类型。

简单使用实例:


import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;
import static java.util.stream.Collector.Characteristics.*;

public class ToListCollector<T> implements Collector<T, List<T>, List<T>> {

    @Override
    public Supplier<List> supplier() {
        return () -> new ArrayList();
    }

    @Override
    public BiConsumer<List, T> accumulator() {
        return (list, item) -> list.add(item);
    }

    @Override
    public Function<List<T>, List<T>> finisher() {
        return i -> i;
    }

    @Override
    public BinaryOperator<List> combiner() {
        return (list1, list2) -> {
            list1.addAll(list2);
            return list1;
        };
    }

    @Override
    public Set characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH, CONCURRENT));
    }
}

你可能感兴趣的:(Java 8 stream 中重要的Collector接口)