Java – How to sort Reducer output?

How to sort Reducer output?… here is a solution to the problem.

How to sort Reducer output?

I want to sort the output of my reducer. An example of my reducer output looks like this:

0,0    2.5
0,1    3.0
1,0    4.0
1,1    1.5

The reducer output is obviously ordered by the first element of the keystroke. But I want the second element of the key to sort it so that the output looks like this:

0,0    2.5
1,0    4.0
0,1    3.0
1,1    1.5

Is there any way to do this?

Please help!

This is my reducer :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class RecReduce extends
Reducer<Text, Text, Text, Text> {
    public static int n=0;
    @Override
    public void setup(Context context) throws IOException, InterruptedException{
        FileSystem hdfs= FileSystem.get(context.getConfiguration());
        BufferedReader br = new BufferedReader(new InputStreamReader(hdfs.open(new Path(context.getConfiguration().get("outFile")))));
        String line=null;
        while((line=br.readLine())!=null){
            n=Integer.parseInt(line);
            break;
        }
        br.close();
        hdfs.close();
    }
    public void reduce(Text key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {
        String[] value;
        HashMap<Integer, Float> hashA = new HashMap<Integer, Float>();
        HashMap<Integer, Float> hashB = new HashMap<Integer, Float>();
        for (Text val : values) {
            value = val.toString().split(",");
            if (value[0].equals("A")) {
                for(int z=1; z<=n; z++){
                    hashA.put(z, Float.parseFloat(value[z])); }
            } else{
                for(int a=1; a<=n; a++){
                    hashB.put(a, Float.parseFloat(value[a])); }
            }
        }
        float result = 0.0f;
        float a_ij;
        float b_jk;
        for (int j=1; j<=n; j++) {
            a_ij = hashA.containsKey(j) ? hashA.get(j) : 0.0f;
            b_jk = hashB.containsKey(j) ? hashB.get(j) : 0.0f;
            result +=a_ij*b_jk;
        }
        context.write(null, new Text(key.toString() + "," + Float.toString(result)));
    }
}

Related Problems and Solutions