@Override
    public Object terminatePartial(AggregationBuffer agg) throws HiveException {
      NGramAggBuf myagg = (NGramAggBuf) agg;
      ArrayList<Text> result = myagg.nge.serialize();

      // push the context on to the end of the serialized n-gram estimation
      for(int i = 0; i < myagg.context.size(); i++) {
        if(myagg.context.get(i) == null) {
          result.add(new Text(""));
        } else {
          result.add(new Text(myagg.context.get(i)));
        }
      }
      result.add(new Text(Integer.toString(myagg.context.size())));

      return result;
    }
A constant-space heuristic to estimate the top-k contextual n-grams.
ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDAFContextNGrams.java