javadictionarycollectionsjava-stream

How to collect data to List<Object> from Map<Object, Integer> of counts using the 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?


Solution

  • 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.