1

I have the following object:

List persons

And I want to create the following structure

List> based on the family name.

I am able to group them in a Map by using groupingBy(p -> p.getFamilyName()). But I would like not to have a map, but a List of Lists.

You can do it in two steps by using the method values() of the map. But I would like to know if you can do it with a collector.

Manuelarte
  • 1,658
  • 2
  • 28
  • 47
  • The best solution is what you are doing, If you want to make it with your idea, It be more complicated than your's take a look at this https://stackoverflow.com/questions/45817262/java-8-how-to-turn-a-list-into-a-list-of-lists-using-lambda – Youcef LAIDANI Apr 26 '18 at 08:01

2 Answers2

3

You can use collectingAndThen:

ArrayList<List<Person>> collect = stream.collect(
    Collectors.collectingAndThen(Collectors.groupingBy(Person::getFamilyName),
                                 m -> new ArrayList<>(m.values())));

This first applies the groupingBy, "and then" creates an ArrayList for each grouped values.

daniu
  • 14,137
  • 4
  • 32
  • 53
1

You could collect using groupingBy and then re-stream the entrySet into your list.

    List<Map.Entry<String, List<Person>>> families = people.stream()
            .collect(Collectors.groupingBy(p -> p.familyName))
            .entrySet()
            .stream()
            .collect(Collectors.toList());
    System.out.println(families);

If you don't need the family name as key then just add .map(e -> e.getValue()) before the final collect:

    List<List<Person>> families = people.stream()
            .collect(Collectors.groupingBy(p -> p.familyName))
            .entrySet()
            .stream()
            .map(e -> e.getValue())
            .collect(Collectors.toList());

or just stream the values:

    List<List<Person>> families = people.stream()
            .collect(Collectors.groupingBy(p -> p.familyName))
            .values()
            .stream()
            .collect(Collectors.toList());
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213