Home > other >  I have Java Map<String,List<String>> and String var, how to return keys whose values(Lis
I have Java Map<String,List<String>> and String var, how to return keys whose values(Lis

Time:09-22

private Set<Integer> keysForValue(Map<Integer, Set<Integer>> map, Integer value) {
    
    Set<Integer> keysSetContainingValue = new HashSet<Integer>();
    
    for (Map.Entry<Integer, Set<Integer>> entry : map.entrySet()) {
        if(entry.getValue().contains(value)) keysSetContainingValue.add(entry.getKey());
    }
    return keysSetContainingValue;
}

CodePudding user response:

Despite the fact that your title saying Map<String, List> while at your code, you are using Map<Integer, Set> ...

    return map.entrySet()
              .stream()
              .filter(entry -> entry.getValue().contains(value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());

CodePudding user response:

It could be slightly better to use keySet() for the map instead of entrySet() to get rid of redundant mapping:

private Set<Integer> keysForValue(Map<Integer, Set<Integer>> map, Integer value) {    
    return map.keySet()
              .stream() // Stream<Integer> of keys
              .filter(k -> map.get(k).contains(value))
              .collect(Collectors.toSet());

}
  • Related