How to print keys with duplicate values in a hashmap?

后端 未结 4 831
天命终不由人
天命终不由人 2021-01-21 22:25

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

4条回答
  •  滥情空心
    2021-01-21 23:12

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

提交回复
热议问题