private void processNgrams(NGramAggBuf agg, ArrayList<String> seq) throws HiveException {
      // generate n-grams wherever the context matches
      assert(agg.context.size() > 0);
      ArrayList<String> ng = new ArrayList<String>();
      for(int i = seq.size() - agg.context.size(); i >= 0; i--) {
        // check if the context matches
        boolean contextMatches = true;
        ng.clear();
        for(int j = 0; j < agg.context.size(); j++) {
          String contextWord = agg.context.get(j);
          if(contextWord == null) {
            ng.add(seq.get(i+j));
          } else {
            if(!contextWord.equals(seq.get(i+j))) {
              contextMatches = false;
              break;
            }
          }
        }

        // add to n-gram estimation only if the context matches
        if(contextMatches) {
          agg.nge.add(ng);
          ng = new ArrayList<String>();
        }
      }
    }
A constant-space heuristic to estimate the top-k contextual n-grams.
ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDAFContextNGrams.java