HeJ小鼠,
我有一个HashMap<Tuple<String, String>, Integer>
形式的HashMap,我想计算元组中第一个String的外观并将其保存为值。
有一种简单的方法吗?因为现在我只能想到复杂的方法,我必须多次迭代地图。
所以基本上我知道如何做到这一点,但我正在寻找一种优雅,可读的方法来做到这一点。
示例:
Input: [(<Apple, today>, null), (<Peach, today>, null), (<Apple, yesterday>, null)]
Output: [(<Apple, today>, 2), (<Peach, today>, 1), (<Apple, yesterday>, 2)]
答案 0 :(得分:0)
到目前为止我的解决方案: (请注释,如果这是一个很好的解决方案或不够可读/优雅)
public HashMap<Tuple<String, String>, Integer> countStuff (HashMap<Tuple<String, String>, Integer> stuffToBeCounted){
HashMap<Tuple<String, String>, Integer> result = new HashMap<Tuple<String, String>, Integer>();
HashMap<String, Integer> countedStuff = new HashMap<String, Integer>();
for (Tuple<String, String> tuple : stuffToBeCounted.keySet()) {
if(countedStuff.containsKey(tuple.v1())){
Integer oldValue = countedStuff.get(tuple.v1());
countedStuff.put(tuple.v1(), oldValue+1);
}
else{
countedStuff.put(tuple.v1(), 1);
}
}
for(Tuple<String, String> tuple : stuffToBeCounted.keySet()){
result.put(tuple, countedStuff.get(tuple.v1()));
}
return result;
}