我想编写一个 MapReduce 程序来打印给定代码的每个字符串的最后一个字

I want to write a MapReduce Program to print the last word of every String of the given code

数据: 1979 23 23 2 43 24 25 26 26 26 26 25 26 25
1980 26 27 28 28 28 30 31 31 31 30 30 30 29
1981 31 32 32 32 33 34 35 36 36 34 34 34 34

映射器:

public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {

    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
               String line = value.toString(); 
         String lasttoken = null; 
         StringTokenizer s = new StringTokenizer(line,"\t"); 
         String year = s.nextToken(); 

         while(s.hasMoreTokens())
            {
               lasttoken=s.nextToken();
            } 

         int val = Integer.parseInt(lasttoken); 
         context.write(new Text(year), new IntWritable(val)); 

      }
    }

减速器:

 public static class Reduce extends MapReduceBase implements Reducer< Text, IntWritable, Text, IntWritable > 

{

  //Reduce function 
  public void reduce( Text key, Iterator <IntWritable> values, 
     OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException 
     { 
       int val=0; 

        while (values.hasNext()) 
        { 
           val=values.next().get(); 
           { 
              output.collect(key, new IntWritable(val)); 
           } 
        } 

我收到 numberFormatException。

异常可能在这里:

int val = Integer.parseInt(lasttoken); 

打印该语句之前的值并查看它是什么。它可能为空、null 或只是一个数字。
尝试在最后一个标记上调用 trim() 是一件好事。这将删除前导和尾随空格。可能是有一些额外的空格或换行符。

无论哪种方式,您都应该检查 lasttoken 是否不为空(如果 s 为空可能会发生),trim 它并使用某些实用程序检查它是一个数字方法或通过捕获 NumberFormatException。以有意义的方式处理它,以防止您的程序崩溃。