title: Get Top N items from mapper output - Mapreduce
body: <p>My Mapper task returns me following output:</p>
  
  <pre><code>2   c
  2   g
  3   a
  3   b
  6   r
  </code></pre>
  
  <p>I have written reducer code and keycomparator that produces the correct output but how do I get Top 3 out (top N by count) of Mapper Output:</p>
  
  <pre><code>public static class WLReducer2 extends
          Reducer&lt;IntWritable, Text, Text, IntWritable&gt; {
  
      @Override
      protected void reduce(IntWritable key, Iterable&lt;Text&gt; values,
              Context context) throws IOException, InterruptedException {
  
          for (Text x : values) {
              context.write(new Text(x), key);
          }
  
      };
  
  }
  
  public static class KeyComparator extends WritableComparator {
      protected KeyComparator() {
          super(IntWritable.class, true);
      }
  
      @Override
      public int compare(WritableComparable w1, WritableComparable w2) {
          // TODO Auto-generated method stub
  
          // Logger.error("--------------------------&gt; writing Keycompare data = -----------&gt;");
          IntWritable ip1 = (IntWritable) w1;
          IntWritable ip2 = (IntWritable) w2;
          int cmp = -1 * ip1.compareTo(ip2);
  
          return cmp;
      }
  }
  </code></pre>
  
  <p>This is the reducer output:</p>
  
  <pre><code>r   6
  b   3
  a   3
  g   2
  c   2
  </code></pre>
  
  <p>The expected output from reducer is  top 3 by count which is:</p>
  
  <pre><code>r   6
  b   3
  a   3
  </code></pre>