考虑简单的类Foo:
public class Foo {
public Float v1;
public Float v2;
public String name;
public Foo(String name, Float v1, Float v2) {
this.name = name;
this.v1 = v1;
this.v2 = v2;
}
public String getName() {
return name;
}
}
现在,我有一个Foos 的集合,我想按 s 对它们进行分组Foo::getName。我写了一个自定义收集器来做到这一点,但它似乎没有按预期工作。更准确地说,combiner()永远不会被调用。为什么?
public class Main {
public static void main(String[] args) {
List<Foo> foos = new ArrayList<>();
foos.add(new Foo("blue", 2f, 2f));
foos.add(new Foo("blue", 2f, 3f));
foos.add(new Foo("green", 3f, 4f));
Map<String, Float> fooGroups = foos.stream().collect(Collectors.groupingBy(Foo::getName, new FooCollector()));
System.out.println(fooGroups);
}
private static class FooCollector implements Collector<Foo, Float, Float> {
@Override
public Supplier<Float> supplier() {
return () -> new Float(0);
}
@Override
public BiConsumer<Float, Foo> accumulator() {
return (v, foo) -> v += foo.v1 * foo.v2;
}
@Override
public BinaryOperator<Float> combiner() {
return (v1, v2) -> v1 + v2;
}
@Override
public Function<Float, Float> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
Set<Characteristics> characteristics = new TreeSet<>();
return characteristics;
}
}
}
翻过高山走不出你
慕沐林林
相关分类