Hashmap无法统计所有出现的情况。
这是来自Hadoop Reduce()的示例代码。
我的映射器键和值是
key---------6.9
v---------------Iris-versicolor
v---------------Iris-virginica
v---------------Iris-virginica
v---------------Iris-versicolor
v---------------Iris-virginica
v---------------Iris-virginica
v---------------Iris-virginica
v---------------Iris-virginica
v---------------Iris-virginica
v---------------Iris-virginica
v---------------Iris-versicolor
v---------------Iris-virginica
v---------------Iris-versicolor
v---------------Iris-versicolor
v---------------Iris-virginica
我的预期结果是
getVal-----------{Iris-versicolor=5, Iris-virginica=10}
但我得到的输出为
getVal-----------{Iris-versicolor=1, Iris-virginica=2}
Sofar我做的是
System.out.println("key---------"+key);
for(Text val:values){
String v = val.toString();
System.out.println("v---------------"+v);
if (getVal.isEmpty()) {
getVal.put(v, 1);
}
else {
for (String colId : getVal.keySet()) {
if(colId.equals(v)){
Integer val1 = getVal.get(colId);
val1 = val1 + 1;
getVal.put(colId, val1);
}
else{
getVal.put(v, 1);
}
}
}
}
System.out.println("getVal-----------"+getVal);
我做错了吗?
答案 0 :(得分:1)
示例:
System.out.println( "key---------" + key );
for ( String value : values ) {
// I used `String` instead of your `Text` type
// so I do not need this line
// String v = value.toString();
System.out.println( "v---------------" + value );
// if the value is not present, add it!
// each value will be added once!
if ( !valueCounterMap.containsKey( value ) )
valueCounterMap.put( value, 1 );
// if the value is already present, just
// increment its counter by 1
else {
Integer counter = valueCounterMap.get( value );
valueCounterMap.put( value, ++counter );
}
}
System.out.println( "getVal-----------" + valueCounterMap );
结果:
getVal-----------{Iris-versicolor=5, Iris-virginica=10}