Mapreduce 标记化 3 列

问题描述

我正在编写一个需要读取 3 列的地图函数我有一个文本文件

1234567 12234254 40

如何在使用 while 循环时更改简单字数映射器的 stringtokenizer 以读取 3 行

public static class TokenizerMapper
   extends Mapper<Object,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); 
  }
}

}

解决方法

该代码与您想要的完全一样,但如 Javadoc 中所述

StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它

改为使用 for 循环

private Text t = new Text();
... 

for (String column : value.toString().split("\\s+")) {
    t.set(column);
    context.write(t,ONE);
}