Find duplicate values ​​in Java Map?

I want to show values ​​in a HashMap . A HashMap can have duplicate values ​​(but not duplicate keys), but I want to display the value only once.

So, I have to find if Map duplicate values. I know that we can map.containsValue(value) over Map and use the returned boolean value map.containsValue(value) . I want to know if there is any method for finding duplicate values ​​on a map or should I write the code myself?

+7
source share
6 answers

A simple solution would be to compare the size of your list of values ​​with the values ​​you set.

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

Example:

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

Output:

 [2, 3, 4] 
+5
source

There is no method like jdk1.6.

One easy way to do this:

  • get all values ​​from the map in the list
  • put this list in a set that will remove duplicates
+1
source

Use apache commons library class method

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

and compare the size of the actual card and the inverted card.

+1
source

Try this code

 private boolean hasDuplicates(Map<Integer, List<String>> datamap){ boolean status = false; Set valueset=new HashSet(datamap.values()); if(datamap.values().size()!=valueset.size()){ status=true; } else{ status = false; } return status; } 
0
source
 try this code but this is not optimize code : public class HashMapDulicate { public static void main(String[] args) { Map<String,Integer> 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<String, Integer> mapVal:map.entrySet()) { if(!set.add(mapVal.getValue())) { list.add(mapVal.getValue()); }else { set.add(mapVal.getValue()); } } for(Entry<String, Integer> mapVal:map.entrySet()) { if(list.contains(mapVal.getValue())){ System.out.println(mapVal.getKey() +":" + mapVal.getValue()); } } } } 
0
source

All Articles