0

Is there any simple way to identify duplicate values in a HashMap?

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

map.put(1, "a");
map.put(2, "a");
map.put(3, "b");

I want to save the duplicate value in a variable named String duplicate. I want the output a.

Thank you all for your help, I'll try your tips. Thanks!

alvira
  • 147
  • 1
  • 7

4 Answers4

2

Try this.

Map<Integer, String> map = Map.of(1, "a", 2, "b", 3, "b", 4,
                "c", 5, "a", 6, "a", 7, "v");
  • Obtain the collection of all the values.
  • Iterate over a set of that collection, removing the first of each value encountered. This leaves only the duplicates in the collection.
  • Then print them as a set showing the duplicates.
Collection<String> all = map.values();
new HashSet<>(all).forEach(all::remove);

System.out.println(new HashSet<>(all));

Prints

[a, b]
        
WJS
  • 36,363
  • 4
  • 24
  • 39
0

In order to get values in Hashmap, you are required to iterate across it. Then you can simply put them in HashSet of String. If you find any value already in HashSet, it is repeated.

Sushant Somani
  • 1,450
  • 3
  • 13
  • 31
0

Using stream API, you can do something like

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

//populate map here
....
//print all values that occur more then 1 time
System.out.println(map.values()
        .stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet()
        .stream()
        .filter(e -> e.getValue() > 1)
        .map(Map.Entry::getKey)
        .collect(Collectors.toSet()));

Output

[a]
rkosegi
  • 14,165
  • 5
  • 50
  • 83
-1

You can iterate over the map values (by first taking them in a list) and look for elements in the list that are occurring more then once by checking if the first and last index particular element is not the same. If its not same, it means that value is present more than once.

Below is the code using Java Stream.

List values = new ArrayList<>(map.values()); Set duplicates = values.stream().filter(item -> values.indexOf(item) != values.lastIndexOf(item)).collect(Collectors.toSet());

  • Taking into an account that `filter()` will iterate the items once - `O(n)` and on each iteration of filter are called `indexOf()` again `O(n)` and `lastIndexOf` - also `O(n)` , you just achieved a total complexity of N * 2N (`O(n^2)`) – Royal Bg Sep 13 '20 at 11:49
  • Yes , you are right. I certainly did not think about performance as it was not clear from the question about the use case of such code. To achieve performance it would be good to sort the array first and just iterate over the list once and compare each element with the next to look for duplicates . – Ketan Nabera Sep 13 '20 at 12:02