關於Mapreduce Text類型賦值的錯誤
Mapreduce中Text類型數據被無緣無故替換?
今天偶然看到一個mapreduce demo,直接上手操作
統計兩個文件中 最大值
文件中數據格式為 名字 數值
輸出為 名字(最大值所對應的名字) 最大值 例如:豪玉 2201
一通編碼,但是居然出現如下的結果
趕緊去查看了代碼,如下
map階段就是找出兩個文件中各自的最大值
//map階段
protected void map(LongWritable key,Text value,Context context) throws IOException,
InterruptedException {
// 拋棄無效記錄
String [] line = value.toString().split(" ");
// 把line轉換為數值
long temp = Long.parseLong(line[1]);
// 比較大小
if (temp >= max) {
name1 = line[0];
// 把val賦值給tempMax
max = temp;
}
}
protected void cleanup(Context context) throws IOException, InterruptedException {
maxValue.set(max);
name.set(name1);
context.write(name,maxValue);
}
reduce階段再進行一次比較
//reduce階段如下
private Long max = Long.MIN_VALUE;
private Text mname = new Text();
private String name;
private Text name2 = new Text();
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException
{
for(LongWritable value : values){
System.out.println(key+value.toString());
if (value.get()>=max)
{
System.out.println("此時的最大值"+value.get());
name2 = key;
max = value.get();
}
}
}
protected void cleanup(Context context) throws IOException, InterruptedException {
// 設置最大值
LongWritable maxValue = new LongWritable();
maxValue.set(max);
mname.set(name2);
context.write(mname,maxValue);
}
於是開始無腦輸出測試
先測試了進入reduce端的數據,無誤
測試進入reduce端 if判斷中的數據,無誤
???
一通改,無果
偶然將 reduce 賦值語句用String類型賦值,發現結果無誤
name = key.toString();
進而開始找尋原因,原來是Text類型賦值的時候需要實例化
name2 = new Text(key);
賦值修改如上,經測試無誤