Aggregate function example: COUNT
Monday, February 28, 2011
1:18 PM
public class COUNT extends EvalFunc<Long> implements Algebraic {
   public Long exec(Tuple input) throws IOException {return count(input);} //??????
   public String getInitial() {return Initial.class.getName();}
   public String getIntermed() {return Intermed.class.getName();}
   public String getFinal() {return Final.class.getName();}
// map step
static public class Initial extends EvalFunc<Tuple> {
public Tuple exec(Tuple input) throws IOException {
return TupleFactory.getInstance().newTuple(count(input));
}
}
// combine step
static public class Intermed extends EvalFunc<Tuple> {
   public Tuple exec(Tuple input) throws IOException {
return TupleFactory.getInstance().newTuple(sum(input));
}
}
// reduce step
static public class Final extends EvalFunc<Long> {
   public Tuple exec(Tuple input) throws IOException {
return sum(input);
}
}
static protected Long count(Tuple input) throws ExecException {
Object values = input.get(0);
if (values instanceof DataBag) return ((DataBag)values).size();
else if (values instanceof Map) return new Long(((Map)values).size());
}
static protected Long sum(Tuple input) throws ExecException, NumberFormatException {
DataBag values = (DataBag)input.get(0);
long sum = 0;
// deal with variable-size tuples
for (Iterator<Tuple> it = values.iterator(); it.hasNext();) {
Tuple t = it.next();
sum += (Long)t.get(0);
}
return sum;
}
}
Pasted from <[link]> 
Some attributes: 
Use of a factory to create new instances: 
TupleFactory.getInstance().newTuple(count(input))
Iterators to iterate over variable-size tuples:
for (Iterator<Tuple> it = values.iterator(); it.hasNext();) {
Tuple t = it.next();
sum += (Long)t.get(0);
}
