9

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

So I should find whether the Map has duplicate values. I know we can iterate over the Map and use the return boolean of map.containsValue(value). I want to know whether any method exists to find duplicate values in map or we should I write code myself?

Nivas
  • 18,126
  • 4
  • 62
  • 76
Silambarasan
  • 299
  • 2
  • 4
  • 14

9 Answers9

24

A simple solution would be to compare the size of your values list with your values 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
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • This tech is fine. but if I want to remove duplicate mean should do manual remove operation right? – Silambarasan Aug 01 '11 at 09:09
  • Yes, you'll have to do a manual operation. But if you can explain me the *exact* scenario, as in how you end up with multiple keys having same value and why you want to remove them, maybe I can propose a better solution. – Sanjay T. Sharma Aug 01 '11 at 10:42
6

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]
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
2

Try out 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;

}
achini
  • 419
  • 4
  • 7
1

Use apache commons library class's method

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

and compare the size of actual map and invert map.

NIrav Modi
  • 6,038
  • 8
  • 32
  • 47
1
public static void main(String[] args) {

        HashMap<String, Integer> map = new HashMap<>();
        map.put("abc", 2);
        map.put("def", 1);
        map.put("hij", 4);
        map.put("klm", 6);
        map.put("nop", 2);
        map.put("qrs", 2);
        map.put("tuv", 6);
        map.put("wxy", 8);
        map.put("zab", 1);
        map.put("cde", 5);
        map.put("fgh", 4);
        map.put("ijk", 3);

        HashMap<Integer, String> duplicatMap = new HashMap<>();

        Set<Entry<String, Integer>> entrySet = map.entrySet();
        Iterator<Entry<String, Integer>> iterator = entrySet.iterator();
        while(iterator.hasNext()) {
            Entry<String, Integer> entry = iterator.next();
            String key = entry.getKey();
            Integer value = entry.getValue();

            if(duplicatMap.containsKey(value)) {
                duplicatMap.put(value, duplicatMap.get(value)+", "+key);
            } else {
                duplicatMap.put(value, key);
            }
        }
        System.out.println(duplicatMap);

    } 

outPut: - {1=def, zab, 2=abc, qrs, nop, 3=ijk, 4=fgh, hij, 5=cde, 6=tuv, klm, 8=wxy} if you want to modify then use again EntrySet.

Mani Kumar
  • 31
  • 4
1

There is no such method provided as of jdk1.6.

One simple way you can do is

  • get all the values from the map in a list
  • put that list into a set which will remove the duplicates
Lucky
  • 16,787
  • 19
  • 117
  • 151
Swagatika
  • 3,376
  • 6
  • 30
  • 39
0
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());
    }
}
    }
}
Pandey Praveen
  • 95
  • 1
  • 2
  • 12
0
Map<Integer,Person> personMap01 = new HashMap<>();
personMap01.put(1,new Person(101,"Ram","Kumar"));
personMap01.put(2,new Person(103,"Raj","Kumar"));
personMap01.put(3,new Person(101,"Ravi","Ram"));
personMap01.put(4,new Person(105,"Gopi","Nath"));
personMap01.put(5,new Person(104,"Yogesh","Waran"));
personMap01.entrySet().stream().
filter(removeDuplicate(personMap01.values())).
forEach(System.out::println);

public static Predicate<Map.Entry<Integer,Person>> 
removeDuplicate(Collection<Person> personCollection){
    return e->Collections.frequency(personCollection,e.getValue())==1;
}
Yogesh
  • 11
  • 1
0

In my one of interview interviewer Asked me to print duplicate without Set, Map and distinct in stream =

List<String> distinctElementList = new ArrayList<>();
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 4, 4, 5, 5, 6);

numberList.stream().forEach(number -> {
        if (distinctElementList.stream().anyMatch(numberStr -> numberStr.contains(String.valueOf(number)))) {
            String existStr = distinctElementList.stream().filter(numberStr -> numberStr.contains(String.valueOf(number))).findFirst().orElse("");
            Integer index = distinctElementList.indexOf(existStr);
            if (existStr.split("[|]").length == 2) {
                distinctElementList.set(index, number + "|" + (Integer.valueOf(existStr.split("[|]")[1]) + 1));
            }
        } else {
            distinctElementList.add(number + "|" + 1);
        }
});

distinctElementList.stream().filter(numberStr -> !numberStr.contains(String.valueOf(1))).forEach(
            numberStr -> {
                String keyValueArr[] = numberStr.split("[|]");
                System.out.println("Number : " + keyValueArr[0] + "--------------Count : "+keyValueArr[1]);
            }
);


System.out.println("Original List : " + numberList);
System.out.println("distinctElementList List : " + distinctElementList); 
alea
  • 980
  • 1
  • 13
  • 18