How to print keys with duplicate values in a hashmap?

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

    Build a Map>, i.e. a Map>.

    Example

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

提交回复
热议问题