Search code examples
lambdajava-8collectors

GroupBy and merge into a single list in java


Java 8 provides a groupingBy function in Collectors, but it gives a map of elements. I need to convert the map into a single list.

Also it returns the result, but instead what I want is to perform the grouping operation to the list itself so that I do not have to reassign it, as reassigning is not possible in a lambda expression.

How can I achieve this?

I want to achieve this:

Map<String, List<Node>> nodeListGrouped = nodeList.stream().collect(Collectors.groupingBy(node -> node.getGroupName()));

convert nodeListGrouped into a single List

But nodeListGrouped.values() returns Collection(List)


Solution

  • I think this is what you are looking for (I have not compiled this though )

    List<Node> list = 
             nodeList.stream()
                     .collect(Collectors.collectingAndThen(
                         Collectors.groupingBy(Node::getGroupName),
                         map -> map.values()
                                   .stream()
                                   .flatMap(List::stream)
                                   .collect(Collectors.toList())
    ));