10

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?

9 Answers 9

26

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
Sign up to request clarification or add additional context in comments.

2 Comments

This tech is fine. but if I want to remove duplicate mean should do manual remove operation right?
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.
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]

2 Comments

How do I add this into the same map
You could ask this as a new question. Please remember to describe clearly what you are trying to achieve, show the code you have tried so far and what exactly goes wrong
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;

}

1 Comment

It should be the best answer !
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

Comments

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.

Comments

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.

1 Comment

It just prints everything.
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());
    }
}
    }
}

Comments

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;
}

1 Comment

Remove Duplicate value(Custom object ) from Map in java8
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); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.