在Java Map中查找重复值?

我想在HashMap显示值。 HashMap可能有重复的值(但不是重复的键),但我想只显示一次值。

所以我应该找到Map是否有重复的值。 我知道我们可以迭代Map并使用map.containsValue(value)的返回布尔map.containsValue(value) 。 我想知道是否有任何方法可以在map中找到重复值,或者我自己应该编写代码?

一个简单的解决方案是将值列表的大小与您设置的值进行比较。

 // pseudo-code List valuesList = map.values(); Set valuesSet = new HashSet(map.values); // check size of both collections; if unequal, you have duplicates 

例:

 Map map = new HashMap(); map.put(1,2); map.put(3,4); map.put(2,2); map.put(5,3); Set uniqueValues = new HashSet(map.values()); System.out.println(uniqueValues); 

输出:

 [2, 3, 4] 

从jdk1.6开始没有提供这样的方法。

你可以做的一个简单方法是

  • 从列表中的地图中获取所有值
  • 将该列表放入一个将删除重复项的集合中

使用apache commons库类的方法

 org.apache.commons.collections.MapUtils.invertMap(map) 

并比较实际地图的大小和反转地图。

试试这段代码

 private boolean hasDuplicates(Map> datamap){ boolean status = false; Set valueset=new HashSet(datamap.values()); if(datamap.values().size()!=valueset.size()){ status=true; } else{ status = false; } return status; } 
 try this code but this is not optimize code : public class HashMapDulicate { public static void main(String[] args) { Map map=new HashMap<>(); map.put("A", 1); map.put("B", 1); map.put("C", 3); map.put("D", 4); Set set=new HashSet<>(); List list=new ArrayList<>(); for(Entry mapVal:map.entrySet()) { if(!set.add(mapVal.getValue())) { list.add(mapVal.getValue()); }else { set.add(mapVal.getValue()); } } for(Entry mapVal:map.entrySet()) { if(list.contains(mapVal.getValue())){ System.out.println(mapVal.getKey() +":" + mapVal.getValue()); } } } }