为什么不能在mapreduce中设置值

x4shl7ld  于 2021-05-29  发布在  Hadoop
关注(0)|答案(0)|浏览(191)

我是mapreduce的初学者。我希望我的reduce过程是这样的:给定一组相同键的输入,比如(key1,100),(key1,#50),(key1,#25),我希望输出(key1,50/100),(key1,25/100)。有“#”的值除以没有“#”的值。
因为我认为(key1100)的位置在Map处理之后可能是未知的。所以我遍历整个集合,得到(key1100)并将#50,#25存储到一个列表中。然后遍历列表,计算50/100,25/100。这样可以吗?这是我的密码:

public static class MyReducer extends Reducer<Text,Text,Text,Text> {
        private Text reskey = new Text();
        private Text resvalue = new Text();
        private List<String> arr = new ArrayList<String>();

        public void reduce(Text key, Iterable<Text> values,
                           Context context
        ) throws IOException, InterruptedException {
            try {
                String prefix = new String(key.toString());

                int total = 0;
                for (Text val : values) {
                    String value = new String(val.toString());
                    if (!value.contains("#")) {
                        total = Integer.parseInt(value);
                    }else{
                        arr.add(value);
                    }
                }

                for (int i = 0 ; i < arr.size() ; ++i) {
                    String value = arr.get(i);
                    if (value.contains("#")) {
                        String[] words = value.split("#");
                        int number = Integer.parseInt(words[1]);
                        double probability = 1.0 * number / total;
                        reskey.set(prefix);
                        resvalue.set(Double.toString(probability));
                        context.write(reskey, resvalue);
                    }
                }
                arr.clear();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

现在的问题是,第二个for循环中的变量“total”始终保持为0。我认为应该在第一个for循环中指定is,因为当我在第一个for循环中打印它时,它不是0。但在第二个for循环中,它变为0(初始值)。原因是什么?谢谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题