3

I have a hashmap with some keys pointing to same values. I want to find all the values that are equal and print the corresponding keys.

This is the current code that I have:

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

    map.put("hello", "0123");
    map.put("hola", "0123");
    map.put("kosta", "0123");
    map.put("da", "03");
    map.put("notda", "013");

    map.put("twins2", "01");
    map.put("twins22", "01");


    List<String> myList = new ArrayList<>();

    for (Map.Entry<String, String> entry : map.entrySet()) {
       for (Map.Entry<String, String> entry2 : map.entrySet()){
           if (entry.getValue().equals(entry2.getValue()))
           {
               myList.add(entry.getKey());
           }
       }

    }

The current code adds the duplicates two times into the list, however it also adds every key one time.

Thanks.

3
  • 1
    stackoverflow.com/a/30741906/493928 Commented Mar 22, 2019 at 23:43
  • Iterate over each entry. Add the value to a new Set and ckeck if the value is already contained in it. This guarantees a runtime of O(n). Commented Mar 22, 2019 at 23:46
  • If you're concerned about performance, you'd better have another HashMap to store your values as keys mapped to an array or a List of keys from the original HashMap. Commented Mar 22, 2019 at 23:54

4 Answers 4

2

You can use streams to retrive duplicates in this way:

  List<String> myList = map.stream()
     .filter(n -> Collections.frequency(map.values(), n) > 1)
     .collect(Collectors.toList());

And then, you can print this out with:

myList.foreach(System.out::println);
Sign up to request clarification or add additional context in comments.

Comments

0

Build a Map<VALUE, List<KEY>>, i.e. a Map<String, List<String>>.

Example

Map<String, String> map = new HashMap<>();
map.put("hello", "0123");
map.put("hola", "0123");
map.put("kosta", "0123");
map.put("da", "03");
map.put("notda", "013");
map.put("twins2", "01");
map.put("twins22", "01");

map.entrySet().stream()
   .collect(Collectors.groupingBy(Entry::getValue,
               Collectors.mapping(Entry::getKey, Collectors.toList())))
   .entrySet().stream()
   .filter(e -> e.getValue().size() > 1)
   .forEach(System.out::println);

Output

01=[twins22, twins2]
0123=[kosta, hello, hola]

Without the filter(), the result would be:

01=[twins22, twins2]
013=[notda]
03=[da]
0123=[kosta, hello, hola]

Comments

0

If you want a solution beside to Stream API;

    public static void duplicatedValuesMap() {
        Map<String, String> map = new HashMap<>();

        map.put("hello", "0123");
        map.put("hola", "0123");
        map.put("kosta", "0123 test");
        map.put("da", "03");
        map.put("notda", "013");
        map.put("twins2", "01");
        map.put("twins22", "01");

        HashMap<String, List<String>> valueToKeyMapCounter = new HashMap<>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (valueToKeyMapCounter.containsKey(entry.getValue())) {
                valueToKeyMapCounter.get(entry.getValue()).add(entry.getKey());
            } else {
                List<String> keys = new ArrayList<>();
                keys.add(entry.getKey());
                valueToKeyMapCounter.put(entry.getValue(), keys);
            }
        }
        for (Map.Entry<String, List<String>> counterEntry : valueToKeyMapCounter.entrySet()) {
            if (counterEntry.getValue().size() > 1) {
                System.out.println("Duplicated Value:" + counterEntry.getKey() + " for Keys:" + counterEntry.getValue());
            }
        }

    }

Comments

0

I think other answers already good to solve the question, i support another method to do just for extended thinking.This method need use Guava's MutliMap interface:

    // init the input map
    Map<String, String> map = new HashMap<>();
    map.put("hello", "0123");
    map.put("hola", "0123");
    map.put("kosta", "0123");
    map.put("da", "03");
    map.put("notda", "013");
    map.put("twins2", "01");
    map.put("twins22", "01");

    // swap key and value of the input map,since different key has same value
    // so we need Multimap
    Multimap<String, String> container = ArrayListMultimap.create();
    map.entrySet().forEach(entry -> container.put(entry.getValue(), entry.getKey()));

    container.keySet().stream()
        .filter(s -> container.get(s).size() > 1).
        forEach(System.out::println);

output:
01
0123

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.