RepeatCount
RepeatCountAggregate 实现了“重复计数”聚合;即重复出现 N 次或更多次的项的数量。
类定义
public static class RepeatCountAggregate implements Aggregate
{
static class Counter
{
int value;
Counter(int val)
{
value = val;
}
}
public void initialize(Object val)
{
accumulate(val);
}
public void accumulate(Object val)
{
Counter counter = occ.get(val);
if (counter == null)
{
counter = new Counter(1);
occ.put(val, counter);
} else {
counter.value += 1;
}
if (counter.value == minOccurrences)
{
count += 1;
}
}
public Object result()
{
return new Long(count);
}
public void merge(Aggregate other)
{
for (Map.Entry<Object,Counter> pair : ((RepeatCountAggregate)other).occ.entrySet())
{
Object key = pair.getKey();
Counter counter = occ.get(key);
if (counter == null)
{
counter = pair.getValue();
occ.put(key, counter);
if (counter.value >= minOccurrences)
{
count += 1;
}
} else {
int oldValue = counter.value;
counter.value += pair.getValue().value;
if (oldValue < minOccurrences && counter.value >= minOccurrences)
{
count += 1;
}
}
}
}
/**
* Constructor of aggregate
* @param minOccurrences minimal number of occurrences
*/
public RepeatCountAggregate(int minOccurrences)
{
this.minOccurrences = minOccurrences;
}
HashMap<Object,Counter> occ = new HashMap<Object,Counter>();
int minOccurrences;
long count;
}