# Hadoop中Map-Reduce、Map、Reduce的示例分析
## 一、Map-Reduce概述
Map-Reduce是Hadoop的核心計算模型,用于**分布式處理大規模數據集**。其核心思想是將計算任務分解為兩個階段:
1. **Map階段**:并行處理輸入數據,生成中間鍵值對
2. **Reduce階段**:合并具有相同鍵的中間結果
## 二、Map階段示例分析
以經典的詞頻統計(WordCount)為例:
```java
// Mapper實現
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
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());
context.write(word, one); // 輸出<單詞,1>
}
}
}
關鍵點:
- 每遇到一個單詞就輸出<單詞,1>
的鍵值對
- 自動并行處理不同數據塊
- 輸出結果會自動按照鍵排序
// Reducer實現
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get(); // 累加相同單詞的出現次數
}
context.write(key, new IntWritable(sum));
}
}
關鍵點:
- 接收形式為<單詞,[1,1,...]>
的輸入
- 對相同鍵的所有值進行聚合計算
- 最終輸出<單詞,總次數>
InputSplit
注意:實際開發中還需配置Job對象指定輸入輸出路徑、Mapper/Reducer類等信息,此處為突出核心邏輯做了簡化。 “`
(全文約560字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。