public ArrayList<Object[]> getNGrams() throws HiveException {
    trim(true);
    if(ngrams.size() < 1) { // SQL standard - return null for zero elements
      return null;
    }

    // Sort the n-gram list by frequencies in descending order
    ArrayList<Object[]> result = new ArrayList<Object[]>();
    ArrayList<Map.Entry<ArrayList<String>, Double>> list = new ArrayList(ngrams.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<ArrayList<String>, Double>>() {
      @Override
      public int compare(Map.Entry<ArrayList<String>, Double> o1,
                         Map.Entry<ArrayList<String>, Double> o2) {
        int result = o2.getValue().compareTo(o1.getValue());
        if (result != 0)
          return result;
        
        ArrayList<String> key1 = o1.getKey();
        ArrayList<String> key2 = o2.getKey();
        for (int i = 0; i < key1.size() && i < key2.size(); i++) {
          result = key1.get(i).compareTo(key2.get(i));
          if (result != 0)
            return result;
        }
        
        return key1.size() - key2.size();
      }
    });

    // Convert the n-gram list to a format suitable for Hive
    for(int i = 0; i < list.size(); i++) {
      ArrayList<String> key = list.get(i).getKey();
      Double val = list.get(i).getValue();

      Object[] curGram = new Object[2];
      ArrayList<Text> ng = new ArrayList<Text>();
      for(int j = 0; j < key.size(); j++) {
        ng.add(new Text(key.get(j)));
      }
      curGram[0] = ng;
      curGram[1] = new DoubleWritable(val.doubleValue());
      result.add(curGram);
    }

    return result;
  }
Returns the final top-k n-grams in a format suitable for returning to Hive.
ql/src/java/org/apache/hadoop/hive/ql/udf/generic/NGramEstimator.java