2022-06-15

https://blog.csdn.net/xiliunian/article/details/88773718

导航

引例

Collector

什么是Collector

Collector工作原理

特征值

自定义Collector

Collectors详解

求值

均值:averaging

元素个数:counting

最值:maxBy、minBy

和:summing、summarizing

分组

groupingBy

groupingByConcurrent

partitioningBy(分区)

其他操作

collectingAndThen

joining

mapping

reducing

toCollection、toList与toSet

toMap与toConcurrentMap

引例
在Java8新特性(二) Stream(流)一文中,由于篇幅有限,有关聚合操作collect使用到的Collector没有展开分析,本文将会详细讲解Collector以及Collectors。

老规矩先来看一个例子。到了收获的季节,农场主需要把果园里的苹果根据颜色分类,然后送往销售商那边。只是将苹果分类是难不倒我们的,下面用代码实现农场主的需求:

public class Apple{

private String color;
private Integer weight;

public Apple(String color, Integer weight) {
    this.color = color;
    this.weight = weight;
}

public String getColor() {
    return color;
}

public Integer getWeight() {
    return weight;
}

@Override
public String toString() {
    return "Apple [color=" + color + ", weight=" + weight + "]";
}

}
public class TestCollectByNormal {

public static List orchard = Arrays.asList(new Apple("green", 150),
        new Apple("red", 170), new Apple("green", 100), new Apple("red", 170), 
        new Apple("yellow", 170), new Apple("green", 150));

public static void main(String[] args) {
    Map> baskets = new HashMap<>();
    for (Apple apple : orchard) {
        String color = apple.getColor();
        List basket = baskets.get(color);
        if (null == basket) {
            basket = new ArrayList<>();
            baskets.put(color, basket);
        }
        basket.add(apple);
    }
    System.out.println(baskets);
}

}
既然我们在学习Java8新特性,不妨用学到的东西来重写上面的例子:

public class TestCollectByOptional {

public static void main(String[] args) {
    Map> baskets = new HashMap<>();
    TestCollectByNormal.orchard.forEach(apple -> {
        List basket = Optional.ofNullable(baskets.get(apple.getColor()))
                .orElseGet(() -> {
                    List tempbasket = new ArrayList<>();
                    baskets.put(apple.getColor(), tempbasket);
                    return tempbasket;
                });
        basket.add(apple);
    });
    System.out.println(baskets);
}

}
比较上面的两种做法,二者的代码量都不少,也不够简洁。下面使用Collector来改进:

public class TestCollectByCollector {

public static void main(String[] args) {
    Map> baskets = TestCollectByNormal.orchard.stream()
            .collect(Collectors.groupingBy(Apple::getColor));
    System.out.println(baskets);
}

}
借助于Collector,我们只用一行代码就完成了上面两种方法中的所有操作。这就是Collector的强大之处。

Collector
什么是Collector
JavaDoc中对Collector的描述如下:

A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.

Collector是一种可变的汇聚操作,它将输入元素累积到一个可变的结果容器中。在所有的元素处理完成后,Collector将累积的结果转换成一个最终的表示(这是一个可选的操作)。Collector支持串行和并行两种方式执行。

Collector接口中声明五个方法和一个枚举常量:

public interface Collector {
Supplier supplier();
BiConsumer accumulator();
BinaryOperator
combiner();
Function finisher();
Set characteristics();
enum Characteristics {
CONCURRENT,
UNORDERED,
IDENTITY_FINISH
}
....
}

Collector接口有三个泛型,它们的含义如下:

T:输入的元素类型
A:累积结果的容器类型
R:最终生成的结果类型
Collector工作原理
Collector通过下面四个方法协同工作以完成汇聚操作:

supplier: 创建新的结果容器
accumulator:将输入元素合并到结果容器中
combiner:合并两个结果容器(并行流使用,将多个线程产生的结果容器合并)
finisher:将结果容器转换成最终的表示
下面是串行流情况下Collector的工作逻辑:

首先supplier会提供结果容器,然后accumulator向结果容器中累积元素,最后finisher将结果容器转换成最终的返回结果。如果结果容器类型和最终返回结果类型一致,那么finisher就可以不执行,这就是之前说这是一个可选的操作的原因。

而combiner是和并行流相关的,在串行流中combiner并不起作用。JavaDoc中介绍如下:

A function that accepts two partial results and merges them. The combiner function may fold state from one argument into the other and return that, or may return a new result container.

combiner方法接受两个部分的结果并合并他们,该方法可能会把一个结果容器折叠到另一个结果容器中并返回,也可能返回一个新的结果容器。

假如在并行流中对元素的操作分别在三条线程中完成,三条线程会返回三个结果容器。此时combiner就可能会这样处理多个线程中的结果容器:先将线程2的结果容器2中元素合并到线程1的结果容器1中,并返回结果容器1;再把线程3的结果容器3中的元素合并到线程1的结果容器1中;最后返回结果容器1。

特征值
除上述四个方法Collector中还有一个characteristics()方法,该方法用于给Collector实现类设置特征值。枚举常量Characteristics 中共有三个特征值,它们的具体含义如下:

CONCURRENT:表示结果容器只有一个(即使是在并行流的情况下)。只有在并行流且收集器不具备此特性的情况下,combiner()返回的lambda表达式才会执行(中间结果容器只有一个就无需合并)。设置此特性时意味着多个线程可以对同一个结果容器调用,因此结果容器必须是线程安全的。
UNORDERED:表示流中的元素无序。
IDENTITY_FINISH:表示中间结果容器类型与最终结果类型一致。设置此特性时finiser()方法不会被调用。

自定义Collector
明白Collector的原理之后,我们就可以自定义Collector实现。下面我们完成一个Collector实现——将输入元素收集到Set集合中。

明确需求之后,我们就可以确定下来Collector实现的三个泛型具体是什么:

T(输入的元素类型):T
A(累积结果的容器类型):Set
R(最终生成的结果类型):Set
完成的Collector实现如下:

public class MySetCollector implements Collector, Set> {

@Override
public Supplier> supplier() {
    System.out.println("supplier invoked");
    return HashSet::new;
}

@Override
public BiConsumer, T> accumulator() {
    System.out.println("accumulator invoked");

// return HashSet::add; // 报错
/**
* 作为accumulator而言,它能明确的仅仅是supplier提供的结果容器类型是Set类型,
* 而不知道supplier提供的具体结果容器类型(这里是HashSet)。
* 如果supplier提供的结果容器类型是TreeSet类型,
* 那么accumulator使用HashSet提供的add方法就会出错。
* 因此这里应该使用Set提供的add方法。
*/
return Set::add;

}

@Override
public BinaryOperator> combiner() {
    System.out.println("combiner invoked");
    return (set1, set2) -> {
        set1.addAll(set2);
        return set1;
    };
}

@Override
public Function, Set> finisher() {
    System.out.println("finisher invoked");
    return Function.identity();   // return t -> t; 
}

@Override
public Set characteristics() {
    System.out.println("characteristics invoked");
    // 结果容器类型和最终结果类型一致,设置IDENTITY_FINISH特性
    return Collections.unmodifiableSet(EnumSet
            .of(Collector.Characteristics.IDENTITY_FINISH));
}

}
测试我们自定义的Collector实现是否发挥了作用:

public class TestMyCollector {

public static void main(String[] args) {
    List data = Arrays.asList("hello", "world", "hello");
    Set result = data.stream().collect(new MySetCollector<>());
    System.out.println(result);
}

}
打印结果如下:

supplier invoked
accumulator invoked
combiner invoked
characteristics invoked
characteristics invoked
[world, hello]

打印结果是符合我们的预期的,但是从打印结果中,我们可以发现两个问题:

1、“finisher invoked”并没有打印,说明finisher()方法没有被调用。

查看collect()方法实现(位于ReferencePipeline类),我们来看该方法是如何调用Collector的:

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);
}

我们在自定义的Collector实现——MySetCollector中设置了IDENTITY_FINISH特性,通过上面的源码可以知道:如果Collector实现中没有IDENTITY_FINISH特性,才会调用实现类中的finisher()方法,否则直接将中间结果容器强转成最终的结果类型。

因此只有在百分百确定中间结果类型和最终的结果类型一致时,才可以为实现类设置IDENTITY_FINISH特性,否则很可能会出现类型转换异常。

2、"combiner invoked"打印了,然而我们的程序中使用的是串行流。

继续跟进到makeRef()方法中:

public static TerminalOp // makeRef部分源码
makeRef(Collector collector) {
Supplier supplier = Objects.requireNonNull(collector).supplier();
BiConsumer accumulator = collector.accumulator();
BinaryOperator combiner = collector.combiner();
....
}

从上面的源码中可以看到,makeRef()方法中用一个变量记录调用combiner()方法返回的Lambda表达式,所以"combiner invoked"会被打印,而该Lambda表达式并没有被调用(可以在此Lambda表达式中加入打印语句验证)。

Collectors详解
Collectors是一个工具类,提供常用的Collector实现。Collectors中定义有实现Collector接口的内部类CollectorImpl,Collectors提供方法的返回值都是CollectorImpl对象。

public final class Collectors {
static class CollectorImpl implements Collector {...}
...
}

求值
均值:averaging
averaging操作可以计算输入元素的均值,该操作包括三个方法:

Collector averagingInt(ToIntFunction mapper)
Collector averagingLong(ToLongFunction mapper)
Collector averagingDouble(ToDoubleFunction mapper)
public class TestCollectors1 {

public static List data = Arrays.asList(new Apple("green", 210), 
        new Apple("red", 170), new Apple("green", 100), new Apple("red", 170), 
        new Apple("yellow", 170), new Apple("green", 150));
 
public static void main(String[] args) {
    Double result = data.stream()
            .collect(Collectors.averagingInt(Apple::getWeight));
    System.out.println(result);
}

}
打印结果如下:

161.66666666666666

元素个数:counting
counting()方法可以统计输入元素的个数。

Collector counting()
public class TestCollectors2 {

public static void main(String[] args) {
    Long result = TestCollectors1.data.stream().collect(Collectors.counting());
    System.out.println(result);
    Long emptyStreamResult = Stream.empty().collect(Collectors.counting());   
    System.out.println(emptyStreamResult);      // 空的流中没有元素,返回0
}

}
打印结果如下:

6
0

值得思考的是,Stream也提供有相同功能的count()方法:

long count = TestCollectors1.appleList.stream().count(); // 该方法返回流中元素个数

为什么在两个地方提供拥有相同功能的方法呢?虽然这两种操作都可以达到相同的目的,但是这两个方法的返回值类型是不同的——count()方法的返回值是long型,counting()方法返回值是Collector类型。在后面谈到分组操作时,我们可以看到counting()方法的返回值又可以作为其他方法的参数,实现更高效的操作。

所以对于同一个目的,可能有多个方法可以实现,我们需要根据情况选择最优的那个。

最值:maxBy、minBy
maxBy和minBy操作可以找出输入元素中的最大最小值。

Collector> minBy(Comparator comparator)
Collector> maxBy(Comparator comparator)
public class TestCollectors3 {

public static void main(String[] args) {
    TestCollectors1.data.stream()
        .collect(Collectors.maxBy(Comparator.comparingInt(Apple::getWeight)))
        .ifPresent(System.out::println);
}

}
打印结果如下:

Apple [color=green, weight=210]

和:summing、summarizing
summing操作可以计算输入元素的总和,该操作包含三个方法:

Collector summingInt(ToIntFunction mapper)
Collector summingLong(ToLongFunction mapper)
Collector summingDouble(ToDoubleFunction mapper)
相较于summing操作只能计算和,summarizing操作则可以提供更强大的计算:该操作可以统计输入元素个数、和以及最值。summarizing操作也提供三个方法:

Collector summarizingInt(ToIntFunction mapper)
Collector summarizingLong(ToLongFunction mapper)
Collector summarizingDouble(ToDoubleFunction mapper)
public class TestCollectors4 {

public static void main(String[] args) {
    testSummingInt();
    testSummarizingInt();
}

private static void testSummingInt() {
    Integer result = TestCollectors1.data.stream()
            .collect(Collectors.summingInt(Apple::getWeight));
    System.out.println(result);
}

private static void testSummarizingInt() {
    System.out.println("===================");
    IntSummaryStatistics result = TestCollectors1.data.stream()
            .collect(Collectors.summarizingInt(Apple::getWeight));
    System.out.println(result);
}

}
打印结果如下:

970

IntSummaryStatistics{count=6, sum=970, min=100, average=161.666667, max=210}

分组
groupingBy
groupingBy操作可以将输入元素进行分组。Collectors提供三个重载的groupingBy()方法:

groupingBy(Function classifier):classifier提供结果Map(HashMap)的键
groupingBy(Function classifier, Collector downstream):downstream提供结果Map和值
groupingBy(Function classifier, Supplier mapFactory, Collector downstream): mapFactory指定结果Map的类型
前面介绍counting()方法的时候说过 :counting()方法的返回值又可以作为其他方法的参数。拥有两个及以上参数的groupingBy()方法,可以接收一个Collector类型参数作为Map的值。这时counting()方法就可以派上用场:

public class TestCollectors5 {

public static void main(String[] args) {
    TreeMap result = TestCollectors1.data.stream()
            .collect(Collectors.groupingBy(Apple::getColor, 
                    TreeMap::new, Collectors.counting()));
    System.out.println(result);
}

}
打印结果如下:

{green=3, red=2, yellow=1}

groupingByConcurrent
具体操作同groupingBy(),将元素整理成ConcurrentMap。

public class TestCollectors6 {

public static void main(String[] args) {
    ConcurrentSkipListMap result = TestCollectors1.data
            .stream().collect(Collectors.groupingByConcurrent(Apple::getColor, 
            ConcurrentSkipListMap::new, Collectors.averagingInt(Apple::getWeight)));
    System.out.println(result);
}

}
打印结果如下:

{green=153.33333333333334, red=170.0, yellow=170.0}

partitioningBy(分区)
分区是分组的一种特殊情况,该操作将输入元素分为两类(即键是true和false的Map)。Collectors提供两个重载的partitioningBy()方法:

partitioningBy(Predicate predicate):predicate提供分区依据
partitioningBy(Predicate predicate,Collector downstream):downstream提供结果Map的值
public class TestCollectors7 {

public static void main(String[] args) {
    Map collect = TestCollectors1.data.stream()
            .collect(Collectors.partitioningBy(
                    apple -> "green".equals(apple.getColor()), 
                    Collectors.averagingInt(Apple::getWeight)));
        System.out.println(collect);
}

}
打印结果如下:

{false=170.0, true=153.33333333333334}

其他操作
collectingAndThen
collectingAndThen()方法接收两个参数:downstream(Collector类型)和finisher(Function类型),在调用downstream之后,将调用结果值作为finisher的传入值,再调用finisher。

collectingAndThen(Collector downstream, Function finisher)
public class TestCollectors8 {

public static void main(String[] args) {
    Optional.ofNullable(TestCollectors1.data.stream().collect(Collectors
            .collectingAndThen(Collectors.averagingInt(Apple::getWeight), 
                    item ->  "average weight is " + item)))
            .ifPresent(System.out::println);
}

}
打印结果如下:

average weight is 161.66666666666666

joining
joining操作可以将输入元素(字符串类型)拼接成字符串。Collectors提三个重载的joining()方法:

joining():拼接输入元素
joining(CharSequence delimiter):将delimiter作为分隔符
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix):将prefix作为前缀,suffix作为后缀
public class TestCollectors9 {

public static void main(String[] args) {
    String result = TestCollectors1.data.stream()
            .map(Apple::getColor).collect(Collectors.joining(",", "Color[", "]"));
    System.out.println(result);     
}

}
打印结果如下:

Color[green,red,green,red,yellow,green]

mapping
mapping()方法接收两个参数:mapper(Function类型)和downstream(Collector类型),在调用mapper之后,将调用结果的返回值作为downstream的输入元素,再调用downstream。

不难发现此方法调用参数的顺序和collectingAndThen()方法相反。

mapping(Function mapper,Collector downstream)
public class TestCollectors10 {

public static void main(String[] args) {
    String result = TestCollectors1.data.stream()
            .collect(Collectors.mapping(Apple::getColor, Collectors.joining()));
    System.out.println(result);
}

}
打印结果如下:

greenredgreenredyellowgreen

reducing
reducing操作可以对输入元素执行汇聚操作。Collectors提供三个重载的reducing()方法:

reducing(BinaryOperator op):对输入的元素应用op操作
reducing(T identity, BinaryOperator op):提供初始值identity
reducing(U identity, Function mapper, BinaryOperator op):在对元素进行op操作之前,先进行mapper操作
public class TestCollectors11 {

public static void main(String[] args) {
    testReducingByOperator();
    testReducingByIdentityAnaOperator();
    testReducingByIdentityAnaOperatorAndFunction();
}

private static void testReducingByOperator() {
    TestCollectors1.data.stream().collect(Collectors
        .reducing(BinaryOperator.maxBy(Comparator.comparingInt(Apple::getWeight))))
            .ifPresent(System.out::println);
}

public static void testReducingByIdentityAnaOperator() {
    System.out.println("===================");
    Integer collect = TestCollectors1.data.stream().map(Apple::getWeight)
            .collect(Collectors.reducing(0, Integer::sum));
    System.out.println(collect);
}

private static void testReducingByIdentityAnaOperatorAndFunction() {
    System.out.println("===================");
    Integer collect = TestCollectors1.data.stream()
            .collect(Collectors.reducing(0, Apple::getWeight, Integer::sum));
    System.out.println(collect);
}

}
打印结果如下:

Apple [color=green, weight=210]

970

970

Stream中也提供汇聚操作reduce,reduce操作强调是不可变性,即输入什么类型元素,输出还是什么类型。而Collectors提供的reducing()方法,则强调的是可变性,输出的类型可以和输入不同。

toCollection、toList与toSet
toCollection、toList和toSet可以将输入元素整理成集合:

toCollection(Supplier collectionFactory):将输入元素整理成集合,collectionFactory可以指定结果集合的类型
toList():将输入元素整理成ArrayList
toSet():将输入元素整理成HashSet
public class TestCollectors12 {

public static void main(String[] args) {
    testToCollection();
    testToList();
    testToSet();
}

private static void testToCollection() {
    LinkedList result = TestCollectors1.data.stream()
        .filter(item -> item.getWeight() > 150)
            .collect(Collectors.toCollection(LinkedList::new));
    System.out.println(result.getClass() + ":" + result);
}

private static void testToList() {
    System.out.println("==============");
    List result = TestCollectors1.data.stream()
        .filter(a -> a.getWeight() > 150).collect(Collectors.toList());
    System.out.println(result.getClass() + ":" + result);
}

private static void testToSet() {
    System.out.println("==============");
    Set result = TestCollectors1.data.stream()
        .collect(Collectors.mapping(Apple::getColor, Collectors.toSet()));
    System.out.println(result.getClass() + ":" + result);
}

}
打印结果如下:

class java.util.LinkedList:[Apple [color=green, weight=210], Apple [color=red, weight=170], Apple [color=red, weight=170], Apple [color=yellow, weight=170]]

class java.util.ArrayList:[Apple [color=green, weight=210], Apple [color=red, weight=170], Apple [color=red, weight=170], Apple [color=yellow, weight=170]]

class java.util.HashSet:[red, green, yellow]

toMap与toConcurrentMap
toMap操作可以将输入元素整理成Map,Collectors提供三个重载的toMap()方法:

toMap(Function keyMapper, Function valueMapper):keyMapper和valueMapper分别提供结果Map的键和值
toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction):mergeFunction对键相同的值进行累积
toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier): mapSupplier可以指定结果的Map类型
toConcurrentMap操作同toMap,这里不再赘述。

需要注意的是,只有两个参数的toMap()(toConcurrentMap)方法的keyMapper所提供的key是不可以重复的,否则会抛出IllegalStateException。

public class TestCollectors13 {

public static void main(String[] args) {
    testToMap();
    testToMapWithBinaryOperatorAndSupplier();
}

private static void testToMap() {
    // 报错:java.lang.IllegalStateException

// Map collect = TestCollectors1.appleList.stream()
// .collect(Collectors.toMap(Apple::getColor, Apple::getWeight));
List data = Arrays.asList(new Apple("green", 210),
new Apple("red", 170), new Apple("yellow", 170));
Map result = data.stream()
.collect(Collectors.toMap(Apple::getColor, Apple::getWeight));
System.out.println(result);
}

private static void testToMapWithBinaryOperatorAndSupplier() {
    System.out.println("==============");
    Hashtable result = TestCollectors1.data.stream()
        .collect(Collectors.toMap(Apple::getColor, 
                v -> 1, Integer::sum, Hashtable::new));
    System.out.println(result);
}

}
打印结果如下:

{red=170, green=210, yellow=170}

{green=3, red=2, yellow=1}
————————————————
版权声明:本文为CSDN博主「zeroxes」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xiliunian/article/details/88773718

你可能感兴趣的:(2022-06-15)