在MapReduce编程中发现Reduce中的迭代器貌似只能使用一次,第二次使用迭代出的数据即为空,很烦恼。其实解决方法很简单:在第一次迭代中就把要迭代的数据保存到一个容器中(例如保存到一个链表中),以后遍历容器(链表),就可以实现在Reduce中多次遍历。 上代码:
Reducer<Text, Text, Text, IntWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String ss=key.toString(); if("score".equals(ss)) { int sum = 0; int count = 0; int min = 150 ; int max = 0 ; int score = 0 ; String name1 = " "; String name2 = " "; List<String> cache =new ArrayList<String>(); for (Text val : values) { cache.add(val.toString()); String[] valTokens = val.toString().split(SPACE); score = Integer.parseInt(valTokens[1]); if (score > max) { max = score; } if (score < min) { min =score; } sum+=score; count++; }新定义一个链表–cache,在第一次对values迭代的时候,把每个元素添加到List中,这样若想再遍历整个values,就可遍历List实现。
