How to collect data to List<Object> from Map<Object,Integer> using java Stream API?

Viewed 103

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?

2 Answers

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.

Stream the entries and use flatMap to generate multiple copies of each key based on the value.

List<Nominal> expanded = map.entrySet().stream()
  .flatMap(e -> generate(e::getKey).limit(e.getValue()))
  .collect(toList());
Related