class Foo { private int variableCount; public Foo(int vars) { this.variableCount = vars; } public Integer getVariableCount() { return variableCount; }}
1、实现accumulator object用于给Collector提供函数
/**
* Accumulator object to hold the current min
* and the list of Foos that are the min.
*/
class Accumulator {
Integer min;
Listfoos;
Accumulator() {
min = Integer.MAX_VALUE;
foos = new ArrayList<>();
}
void accumulate(Foo f) {
if (f.getVariableCount() != null) {
if (f.getVariableCount() < min) {
min = f.getVariableCount();
foos.clear();
foos.add(f);
} else if (f.getVariableCount() == min) {
foos.add(f);
}
}
}
Accumulator combine(Accumulator other) {
if (min < other.min) {
return this;
}
else if (min > other.min) {
return other;
}
else {
foos.addAll(other.foos);
return this;
}
}
ListgetFoos() { return foos; }
}
2、调用方法和测试
1)示例List
Listfoos = Arrays.asList(new Foo(3), new Foo(3), new Foo(2), new Foo(1), new Foo(1), new Foo(4));
2)调用方法
Listmins = foos.stream().collect(Collector.of( Accumulator::new, Accumulator::accumulate, Accumulator::combine, Accumulator::getFoos ));
输出结果:
[Foo{1}, Foo{1}]