0

Given the following map declaration Map<Integer, List<Integer>> I want to use Java 8 streams API to collect all the key-value pairs into a List<Integer> using a single stream iteration. For example, given the following mapping:

1->[2,3] 
4->[7,8]

The resulting list would be: [1,2,3,4,7,8]

Daniel Nitzan
  • 1,582
  • 3
  • 19
  • 36

1 Answers1

4
List<Integer> list = map.entrySet()
        .stream()
        .flatMap(e -> Stream.concat(Stream.of(e.getKey()), e.getValue().stream()))
        .collect(Collectors.toList());
shmosel
  • 49,289
  • 6
  • 73
  • 138