title: Hadoop MapReduce: return sorted list of words in a text file
body: <p>So my task is to return a alpahbetically sorted list of all words contained in a text file while keeping duplicates.</p>
  
  <p>{To be or not to be} −→ {be be not or to to}</p>
  
  <p>My idea is to take each word as the key as well as the value. This way, because hadoop sorts the keys, they will automatically be sorted alphabtically. In the Reduce phase I simply append all words with the same key (so basically identical words) to one single Text value.</p>
  
  <pre><code>   public class WordSort {
  
     public static class Map extends Mapper&lt;LongWritable, Text, Text, Text&gt; {
  
     private Text word = new Text();
  
     public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        StringTokenizer tokenizer = new StringTokenizer(line);
        while (tokenizer.hasMoreTokens()) {
          word.set(tokenizer.nextToken());
          // transform to lower case
          String lower = word.toString().toLowerCase();
          context.write(new Text(lower), new Text(lower));
        }
      }
    }
  
    public static class Reduce extends Reducer&lt;Text, Text, Text, Text&gt; {
  
    public void reduce(Text key, Iterable&lt;Text&gt; values, Context context) throws IOException, InterruptedException {
        String result = "";
        for (Text value : values){
           res += value.toString() + " ";
        }
        context.write(key, new Text(result));
      }
    }
  </code></pre>
  
  <p>However my problem is, how do I simply return the value in my output file? At the moment I have this:</p>
  
  <pre><code>be be be 
  not not 
  or or
  to to to
  </code></pre>
  
  <p>So in every line I have the key first and then the values, but I just want to return the values so that I get this:</p>
  
  <pre><code>be be
  not 
  or 
  to to
  </code></pre>
  
  <p>Is this even possible or do I have to just delete one entry from the value of each word?</p>