Silambarasan
Silambarasan

Reputation: 309

Find duplicate values in Java Map?

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?

Upvotes: 10

Views: 77514

Answers (9)

user21840875
user21840875

Reputation: 1

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

Upvotes: 0

Yogesh
Yogesh

Reputation: 11

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

Upvotes: 0

Mani Kumar
Mani Kumar

Reputation: 51

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.

Upvotes: 1

Pandey Praveen
Pandey Praveen

Reputation: 95

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

Upvotes: 0

achini
achini

Reputation: 449

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;

}

Upvotes: 2

NIrav Modi
NIrav Modi

Reputation: 6962

Use apache commons library class's method

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

and compare the size of actual map and invert map.

Upvotes: 1

Swagatika
Swagatika

Reputation: 3436

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

Upvotes: 1

Adriaan Koster
Adriaan Koster

Reputation: 16209

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]

Upvotes: 6

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

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

Upvotes: 26

Related Questions