lst = [and, and, and, and, these, those, their, boxes, boxes]
public Collection<Character> 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);
}
}
System.out.println(hashmap);
hashmap = {a=4, b=2, t=3}
现在如何获取哈希图以仅返回具有最高相关性值的键。
所需的输出:
[a]
一种方法可能是:
Collection<Integer> values = hashmap.values(); // get values
List<Integer> listVal = new ArrayList<Integer>(values);
Collections.sort(listVal, new Comparator<Integer>() { // sort in decreasing order
public int compare(Integer o1, Integer o2) {
return - o1.compareTo(o2);
}
});
Integer maxVal = listVal.get(0); // get first (max value)
Collection<Character> returns = new ArrayList<Character>();
for (Map.Entry<Character, Integer> entry : hashmap.entrySet()) {
if (entry.getValue().intValue() == maxVal.intValue()) {
returns.add(entry.getKey()); // get all keys that matches maxVal
}
}
return returns;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句