小編典典
如果這是經常需要的功能,我們最好做一個Collector。我們将需要一個Stats類來儲存count, min,
max,并需要使用工廠方法來建立統計收集器。
Stats stats = stringStream.collect(Stats.collector())
fooStream.collect(Stats.collector(fooComparator))
(也許更好的便捷方法是Stats.collect(stream))
我做了一個示例Stats課-
https://gist.github.com/zhong-j-
yu/ac5028573c986f7820b25ea2e74ed672
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, Stats> collector()
{
return collector(Comparator.naturalOrder());
}
}
2020-11-13