java : get count of all distinct keys and values in Map<String,Set<String>>

Viewed 73

input: Map<String, Set> map

eg: map =

    {"a"=[], 
    "b"=["b", "1", "2", "4"]}

expected output : 5 ("b" appears as key and value. should be counted as one)

this is what i have tried so far. is there a better way to do this?

    Set<String> o = new HashSet<String>();
    o.addAll(m1.keySet());
    o.addAll(m1.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()));
    System.out.println(o.size());

Is it possible to stream on the map's entryset to arrive at this output? Also creating a separate hashset looks unnecessary just to get a count

1 Answers

You can do something like this:

Set<String> o = m1.entrySet()
                  .stream()
                  .flatMap(e -> Stream.concat(Stream.of(e.getKey()),e.getValue().stream()))
                  .collect(Collectors.toSet());

i.e. create a Stream<String> of each entry of the Map.

Related