从 HashMap 中的所有集合中获取公共(public)值的最快方法是什么?
我有一个
Map<String, Set<String>>
我检查键 并获取所有具有给定键的集合。但是,除了从 hashmap 中获取所有集合,有没有更好的方法从所有集合中获取公共(public)元素(值)?
例如,hashmap包含,
abc:[ax1,au2,au3]
def:[ax1,aj5]
ijk:[ax1,au2]
我想单独提取 ax1
和 au2
,因为它们是集合中最常见的值。
最佳答案
注意:不确定这是否是最快的,但这是一种方法。
首先,编写一个简单的方法来提取出现在映射中所有值集的字符串的频率。这是一个简单的实现:
Map<String, Integer> getFrequencies(Map<String, Set<String>> map) {
Map<String, Integer> frequencies = new HashMap<String, Integer>();
for(String key : map.keySet()) {
for(String element : map.get(key)) {
int count;
if(frequencies.containsKey(element)) {
count = frequencies.get(element);
} else {
count = 1;
}
frequencies.put(element, count + 1);
}
}
return new frequencies;
}
您可以像这样简单地调用此方法:Map<String, Integer> frequencies = getFrequencies(map)
其次,为了得到frequencies
中最“常见”的元素 map ,您只需使用 Comparator interface 对 map 中的条目进行排序.碰巧 SO 有一个优秀的社区 wiki 来讨论这个问题:Sort a Map<Key, Value> by values (Java) . wiki 包含多个有趣的问题解决方案。复习一下它们可能会有所帮助。
你可以简单地实现一个类,称之为FrequencyMap
, 如下所示。
让类实现 Comparator<String>
接口(interface),因此 int compare(String a, String b)
方法使 map 的元素按值整数的递增顺序排序。
第三,实现另一个方法,调用它getCommon(int threshold)
并传递给它一个阈值。 map 中频率值大于 threshold
的任何条目, 可以被认为是“常见的”,并将作为一个简单的列表返回。
class FrequencyMap implements Comparator<String> {
Map<String, Integer> map;
public FrequencyMap(Map<String, Integer> map) {
this.map = map;
}
public int compare(String a, String b) {
if (map.get(a) >= map.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
public ArrayList<String> getCommon(int threshold) {
ArrayList<String> common = new ArrayList<String>();
for(String key : this.map.keySet()) {
if(this.map.get(key) >= threshold) {
common.add(key);
}
}
return common;
}
@Override public String toString() {
return this.map.toString();
}
}
所以使用 FrequencyMap 类和 getCommon
方法,归结为以下几行代码:
FrequencyMap frequencyMap = new FrequencyMap(frequencies);
System.out.println(frequencyMap.getCommon(2));
System.out.println(frequencyMap.getCommon(3));
System.out.println(frequencyMap.getCommon(4));
对于您问题中的示例输入,这是您获得的 o/p:
// common values
[ax1, au6, au3, au2]
[ax1, au2]
[ax1]
此外,这里有一个要点,其中包含我为这个问题编写的代码:https://gist.github.com/VijayKrishna/5973268
关于java - 从 Java 中集合的 HashMap 中找到最常见的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584008/