How to print keys with duplicate values in a hashmap?

后端 未结 4 827
天命终不由人
天命终不由人 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:00

    If you want a solution beside to Stream API;

        public static void duplicatedValuesMap() {
            Map 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> valueToKeyMapCounter = new HashMap<>();
    
            for (Map.Entry entry : map.entrySet()) {
                if (valueToKeyMapCounter.containsKey(entry.getValue())) {
                    valueToKeyMapCounter.get(entry.getValue()).add(entry.getKey());
                } else {
                    List keys = new ArrayList<>();
                    keys.add(entry.getKey());
                    valueToKeyMapCounter.put(entry.getValue(), keys);
                }
            }
            for (Map.Entry> counterEntry : valueToKeyMapCounter.entrySet()) {
                if (counterEntry.getValue().size() > 1) {
                    System.out.println("Duplicated Value:" + counterEntry.getKey() + " for Keys:" + counterEntry.getValue());
                }
            }
    
        }
    

提交回复
热议问题