【问题标题】:finding key with maximum value in java mapreduce在java mapreduce中找到最大值的键
【发布时间】:2018-02-27 07:13:09
【问题描述】:

我正在尝试查找具有最大值的键,但每次说无法将文本转换为字符串时都会生成错误。这和java mapreduce有关。

错误: TaskInputOutputContext 类型中的 write(Text, IntWritable) 方法不适用于参数 (String, IntWritable)

列表

994290  5  
994380  33  
994410  1  
994440  11  
995010  2  
995030  5  

预期

994380  33  

代码

@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context)
        throws IOException, InterruptedException {

    int max = 0;
    String keyWithMax = "";
    for (IntWritable value : values) {
        if (value.get() > max) {
            max = value.get();
            keyWithMax = key.toString();
        }
    }
    context.write(keyWithMax, new IntWritable(max));
}

你能帮帮我吗?

【问题讨论】:

  • 请检查我的答案。希望对您有所帮助。

标签: java mapreduce


【解决方案1】:

我认为你不需要对key 做任何事情,你可以直接使用它传入

@Override
public void reduce(Text key, Iterable<IntWritable> values,
                   Context context)
                   throws IOException, InterruptedException {
    int max= 0;
    for (IntWritable value : values) {
        if(value.get() > max){
          max= value.get();
        }
    }
    context.write(key, new IntWritable(max));
  }

【讨论】:

  • 嗨 avigil,上面修改过的代码正在显示具有最小值的键。你能看一下吗?
  • 这个reduce步骤将找到单个键的最大值,您仍然需要一个额外的步骤来找到所有键中的最大值。
  • 嗨,Avigil,你能帮我写几行代码吗...由于我是 Java 和大数据的新手,我有点困惑...提前致谢跨度>
【解决方案2】:

您将keyWithMax 传递给context.write() 方法,这是一个String 类型。它期望 Text() 类型的数据作为键。

问题在于context.write(keyWithMax, new IntWritable(max)); 行 改成context.write(new Text(keyWithMax), new IntWritable(max));

或者更好的是,为输出键定义一个全局变量为

private Text outKey= new Text();

并在写入上下文之前设置它

outKey.set(keyWithMax);

这是因为创建new Text() 比创建一次并重复使用更昂贵。 new IntWritable(max) 也是如此。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2016-01-28
    • 1970-01-01
    • 2011-07-11
    • 2011-08-20
    • 2016-04-24
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多