Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.util.StringTokenizer;
- import java.util.TreeMap;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.fs.Path;
- import org.apache.hadoop.io.IntWritable;
- import org.apache.hadoop.io.LongWritable;
- import org.apache.hadoop.io.NullWritable;
- import org.apache.hadoop.io.Text;
- import org.apache.hadoop.mapreduce.Job;
- import org.apache.hadoop.mapreduce.Mapper;
- import org.apache.hadoop.mapreduce.Reducer;
- import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
- import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
- public class Transpose {
- public static class TransposeMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
- @Override
- protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
- long column = 0;
- long somethingLikeRow = key.get();
- for (String num : value.toString().split(",")) {
- context.write(new LongWritable(column), new Text(somethingLikeRow + "\t" + num));
- ++column;
- }
- }
- }
- public static class TransposeReducer extends Reducer<LongWritable, Text, Text, NullWritable> {
- @Override
- protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
- TreeMap<Long, String> row = new TreeMap<Long, String>(); // storing values sorted by positions in input file
- for (Text text : values) {
- String[] parts = text.toString().split("\t"); // somethingLikeRow, value
- row.put(Long.valueOf(parts[0]), parts[1]);
- }
- String rowString = StringUtils.join(row.values(), ' '); // i'm using org.apache.commons library for concatenation
- context.write(new Text(rowString), NullWritable.get());
- }
- }
- public static void main(String[] args) throws Exception {
- Configuration conf = new Configuration();
- Job job = Job.getInstance(conf, "Transpose");
- job.setJarByClass(Transpose.class);
- job.setMapperClass(TransposeMapper.class);
- job.setCombinerClass(TransposeReducer.class);
- job.setReducerClass(TransposeReducer.class);
- job.setOutputKeyClass(LongWritable.class);
- job.setOutputValueClass(Text.class);
- FileInputFormat.addInputPath(job, new Path(args[0]));
- FileOutputFormat.setOutputPath(job, new Path(args[1]));
- System.exit(job.waitForCompletion(true) ? 0 : 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement