如果这是一个经常需要的功能,我们最好让收藏家做这个工作.我们需要一个Stats类来保持count,min,max和factory方法来创建统计数据收集器.
Stats stats = stringStream.collect(Stats.collector())
fooStream.collect(Stats.collector(fooComparator))
(也许更好的方便方法是Stats.collect(stream))
我举了一个例子Stats class –
public class Stats
{
int count;
final Comparator super T> comparator;
T min;
T max;
public Stats(Comparator super T> comparator)
{
this.comparator = comparator;
}
public int count(){ return count; }
public T min(){ return min; }
public T max(){ return max; }
public void accept(T val)
{
if(count==0)
min = max = val;
else if(comparator.compare(val,min)<0)
min = val;
else if(comparator.compare(val,max)>0)
max = val;
count++;
}
public Stats combine(Stats that)
{
if(this.count==0) return that;
if(that.count==0) return this;
this.count += that.count;
if(comparator.compare(that.min,this.min)<0)
this.min = that.min;
if(comparator.compare(that.max,this.max)>0)
this.max = that.max;
return this;
}
public static Collector,Stats> collector(Comparator super T> comparator)
{
return Collector.of(
()->new Stats<>(comparator),Stats::accept,Stats::combine,Collector.Characteristics.UNORDERED,Collector.Characteristics.IDENTITY_FINISH
);
}
public static > Collector> collector()
{
return collector(Comparator.naturalOrder());
}
}