我遇到了Hadoop中多个for-each循环的问题,甚至可能吗?
我现在对 reducer 类具有什么代码:
public class R_PreprocessAllSMS extends Reducer<Text, Text, Text, Text>{
private final static Text KEY = new Text();
private final static Text VALUE = new Text();
@Override
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (Text value : values) {
String[] splitString = value.toString().split("\t");
sum += Integer.parseInt(splitString[1]);
}
if (sum > 100) {
for (Text value : values) {
String[] splitString = value.toString().split("\t");
System.out.println(key.toString() + splitString[0] + " " + splitString[1]);
KEY.set(key);
VALUE.set(splitString[0] + "\t" + splitString[1]);
context.write(KEY, VALUE);
}
}
}
}
但是我想有可能第二次搜索给定值并发出我们需要的值。如果不可能,您建议在Hadoop中执行此操作的推荐方法是什么?
谢谢。
最佳答案
您可以延迟写入值,直到知道总和足够高为止,而不是循环两次,例如:
int sum = 0;
List list = new ArrayList<String>();
KEY.set(key);
for (Text value : values) {
String[] splitString = value.toString().split("\t");
String line = splitString[0] + "\t" + splitString[1];
sum += Integer.parseInt(splitString[1]);
if (sum < 100) {
list.add(line);
} else {
if (!list.isEmpty()) {
for (String val: list) {
VALUE.set(val);
context.write(KEY, VALUE);
}
list.clear();
}
VALUE.set(line);
context.write(KEY, VALUE);
}
}
关于java - Hadoop Reducer中的多个for-each循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21309177/