【问题标题】:how to write int values in hadoop reducer如何在 hadoop reducer 中写入 int 值
【发布时间】:2014-01-11 10:57:15
【问题描述】:

我正在用 Hadoop 编写 ma​​preduce。 在 reduce 方法中,我想使用 context.write() 。但输出是 int 类型。 我怎样才能做到这一点?当我使用 context.write() 时显示错误:

第二个参数不能是 int。

这是我的代码:

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

            int count = 0;

            for (NullWritable nullWritable : values) {
                count++;
            }

             //context.write(key, count); 
}

这个减少很重要。然后它应该写 key 和 count 变量。

我该怎么做?

回答

我找到了答案。我应该new一个IntWritable类并使用它的方法(set(intValue))。

如下代码:

IntWritable c = new IntWritable();
    public void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {

                int count = 0;


                for (NullWritable nullWritable : values) {
                    count++;
                }

                c.set(count);
                context.write(key, c);

            }

【问题讨论】:

    标签: hadoop mapreduce


    【解决方案1】:

    你也可以这样使用:

    context.write(key,new IntWritable(count));
    

    【讨论】:

    • 谢谢。但是会浪费内存!如果你的 reduce 调用了很多次,它会创建新对象并浪费内存......但是谢谢;)
    • 您的 reducer 将被调用的次数与数据中唯一键的次数一样多。注意。无论如何,它并不像 map 那样占用那么多内存,mapreduce 是内存和 CPU 密集型任务,所以你应该记住这一点
    猜你喜欢
    • 2012-01-14
    • 1970-01-01
    • 2018-04-02
    • 2012-06-16
    • 2018-02-10
    • 1970-01-01
    • 2012-05-30
    • 2012-11-14
    • 1970-01-01
    相关资源
    最近更新 更多