在Java中,可以使用MapReduce框架來按鍵值合并數據。以下是一個簡單的示例代碼:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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 KeyValueMerge {
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer
extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values,
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "key value merge");
job.setJarByClass(KeyValueMerge.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
在這個示例中,我們定義了一個TokenizerMapper
類作為Map任務,通過StringTokenizer
將輸入的文本拆分為單詞,并將每個單詞作為鍵,值設置為1,然后將鍵值對輸出給Reducer任務。
Reducer任務由IntSumReducer
類實現,它接收相同鍵的一組值,并將它們相加,然后輸出鍵值對。
在main
方法中,我們設置了作業的各種參數,包括輸入路徑、輸出路徑以及使用的Mapper和Reducer類等。
要使用MapReduce框架運行這個示例,您需要將代碼打包成一個JAR文件,并在Hadoop集群上運行它。假設您已經安裝并配置了Hadoop集群,可以使用以下命令來運行這個示例:
hadoop jar KeyValueMerge.jar KeyValueMerge <input-dir> <output-dir>
其中KeyValueMerge.jar
是您打包的JAR文件,<input-dir>
是輸入目錄,<output-dir>
是輸出目錄。