应该调用我的方法
Public Collection<Character> mostCommonFirstWeighted()
但我解决问题的方法是让它返回
List<Map.Entry<Character, Integer>>
如何修复此问题,以便我的返回语句是一组字符?
public List<Map.Entry<Character, Integer>> mostCommonFirstWeighted() {
HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
for (String s : lst) {
if (hashmap.get(s.charAt(0)) == null) {
hashmap.put(s.charAt(0), 1);
} else {
hashmap.put(s.charAt(0), hashmap.get(s.charAt(0)).intValue() + 1);
}
}
Integer largestVal = null;
List<Map.Entry<Character, Integer>> largestList = new ArrayList<Map.Entry<Character, Integer>>();
for (Map.Entry<Character, Integer> i : hashmap.entrySet()) {
if (largestVal == null || largestVal < i.getValue()) {
largestVal = i.getValue();
largestList.clear();
largestList.add(i);
} else if (largestVal == i.getValue()) {
largestList.add(i);
}
}
return largestList;
}
}
示例输入:[和,和,和,以及这些,它们,盒子,盒子]
预期结果:[a]
得到的结果:[a = 4]
答案 0 :(得分:2)
更改
List<Map.Entry<Character, Integer>> largestList = new ArrayList<Map.Entry<Character, Integer>>();
到
List<Character> largestList = new ArrayList<Character>();
largestList.add(i);
(两者都是)largestList.add(i.getKey());