我创建了2个HashMaps,用于存储来自两个txt文件的字符串值。我能够成功打印两个地图中重复的值,但是,我无法确定每个值重复的次数。
以下是我的代码,用于识别重复值:
// find if hashmaps contain duplicate values
boolean val = wordsMap.keySet().containsAll(wordsMap1.keySet());
// create new entry for hashmap
for (Entry<String, Integer> str : wordsMap.entrySet()) {
System.out.println("================= " + str.getKey());
if(wordsMap1.containsKey(str.getKey())){
System.out.println("Map2 Contains Map 1 Key");
}
}
System.out.println("================= " + val);
有什么建议吗?谢谢
我正在考虑
的内容Map.values().equals(Map1.values()){
count++;
}
答案 0 :(得分:0)
如果我理解正确,您希望找到两个地图对象共有的值。 (根据需要添加null
和/或其他检查)
public static int duplicateCount(Map<String, Integer> m1, Map<String, Integer> m2) {
int count = 0;
Collection<Integer> m1Values = m1.values();
Collection<Integer> m2Values = m2.values();
for (Integer i : m1Values) {
if (m2Values.contains(i)) {
count++;
}
}
return count;
}
答案 1 :(得分:0)
获取地图之间的重复键数量
public static int getDuplicateKeyCount(Map<?, ?> m1, Map<?, ?> m2) {
Set<?> tempSet = new HashSet<>(m1.keySet());
tempSet.retainAll(new ArrayList<>(m2.keySet()));
return tempSet.size();
}
获取地图之间的重复值数量
public static int getDuplicateValueCount(Map<?, ?> m1, Map<?, ?> m2) {
List<?> tempList = new ArrayList<>(m1.values());
tempList.retainAll(m2.values());
return tempList.size();
}
获取包含m2的值的m1频率的地图
public static <K, V> Map<V, Integer> getValueFrequencyMap(Map<K, V> m1, Map<K, V> m2) {
Map<V, Integer> freq = new HashMap<>();
Collection<V> col = m2.values();
for(V val : m1.values()) {
freq.put(val, Collections.frequency(col, val));
}
return freq;
}
答案 2 :(得分:0)
以下是根据我对您的疑问的理解编写的示例程序。它查找并显示重复键以及重复值及其重复频率。逻辑是:要查找频率,请将复制元素从 map1 和 map2 作为参数传递给 countFrequency()方法,该方法在转弯将返回重复次数。
package com.rahul.stackoverflow;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class DuplicateValHashMap {
public static void main(String[] args) {
Map<String, Integer> map1 = new HashMap<String, Integer>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
map1.put("A", 1);
map1.put("B", 2);
map1.put("C", 3);
map1.put("D", 4);
map1.put("E", 5);
map2.put("A", 1);
map2.put("F", 2);
map2.put("G", 1);
map2.put("H", 3);
map2.put("B", 2);
for(Entry<String, Integer> entrySet : map1.entrySet()){
if(map2.containsKey(entrySet.getKey())){
System.out.println("Map2 contains keys of map1.");
System.out.println("Duplicate keys are : " + entrySet.getKey());
}
if(map2.containsValue(entrySet.getValue())){
System.out.println("Map2 contains values of map1.");
System.out.println("Duplicate values are : " + entrySet.getValue()+
" which is repeated " + countFrequency(map2, entrySet.getValue())+ " times.");
}
}
}
public static int countFrequency(Map<String, Integer> map, Integer value){
int count = 0;
for(Entry<String, Integer> entrySet : map.entrySet()){
if(value == entrySet.getValue()){
count++;
}
}
return count;
}
}