Skip to content
Advertisement

How to collect data to List from Map using java Stream API?

I have map Map<Nominal, Integer> with objects and their counts:

a -> 3
b -> 1
c -> 2

And I need to get such a List<Nominal> from it:

a
a
a
b
c
c

How can I do this using the Stream API?

Advertisement

Answer

We can use Collections::nCopies to achieve the desired result:

private static <T> List<T> transform(Map<? extends T, Integer> map) {
  return map.entrySet().stream()
      .map(entry -> Collections.nCopies(entry.getValue(), entry.getKey()))
      .flatMap(Collection::stream)
      .collect(Collectors.toList());
}

Ideone demo


Remark

In the demo, I changed the key-type of the Map from Nominal to Object since the definition of Nominal was not provided. Changing the key-type, however, does not influence the solution.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement