3

I have a hash map

Map<Integer, List<String>> Directmap = new HashMap<Integer, List<String>>() {{
    put(0, Arrays.asList(a, b));
    put(1, Arrays.asList(b, c));
    put(2, Arrays.asList(d));
    put(3, Arrays.asList(d, e));
    put(4, Arrays.asList(e));
    put(5, Arrays.asList());
}};

Directmap: {0=[a, b], 1=[b, c], 2=[d], 3=[d, e], 4=[e], 5=[]}

I want to count the number of keys for each value. For example: "a" has one key, "b" has two keys, ..., "e" has two keys namely 3 and 4.

I tried something like this:

Map<Object, Long> ex = Directmap.entrySet().stream()
            .collect(Collectors.groupingBy(e -> e.getKey(), Collectors.counting()));

I want the values with number of keys as the output. Like this :

a=[1], b=[2], c=[1], d=[2], e=[2]
Tunaki
  • 132,869
  • 46
  • 340
  • 423
priya
  • 375
  • 5
  • 22

1 Answers1

7

You can do this by flat mapping each value of the map.

In this code, only the values of the map are kept (since you are not interested in the keys). Each value, which is a List<String> is flat mapped so that the Stream pipeline, which is Stream<List<String>> becomes Stream<String>. Finally, the Stream is grouped by (groupingBy) the identity function and the reduction performed on the elements is just counting the number of occurences (counting()).

Map<String, Long> ex = 
      Directmap.values()
               .stream()
               .flatMap(Collection::stream)
               .collect(Collectors.groupingBy(v -> v, Collectors.counting()));

Note that if a value is appearing twice in the initial map, it will also counted twice. If you want to count the number of distinct values, you can add a call to distinct() before collecting the result (or use a Set instead of a List).

Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • 1
    But this won’t count the *keys*, e.g. if a value appears multiple times in a list, it will be counted multiple times despite having the same key. Adding a `distinct` doesn’t help as then, each value will be “counted” exactly once, even when it occurs at different keys. – Holger Dec 30 '15 at 10:56
  • @Tunaki [link] (http://stackoverflow.com/questions/34575726/how-to-sort-hash-map-based-on-number-of-keys-for-a-value-using-flatmap-java8#comment56897375_34575726) I have a asked a question based on this post. Could you please check this link too. – priya Jan 03 '16 at 12:32