How can I group Stream<Person> into Stream<List<Person>>, not into Map<String, <List<Person>>?

119 views Asked by At

I have POJO class:

@Data
@AllArgsConstructor
public class Person {
    private String name;
    private String surname;
}

I have some executable code:

public class Main {

    public static void main(String[] args) {
        Person john1 = new Person("John", "Smith");
        Person john2 = new Person("John", "Brown");
        Person nancy1 = new Person("Nancy", "James");
        Person nancy2 = new Person("Nancy", "Williams");
        Person kate1 = new Person("Kate", "Fletcher");

        List<Person> persons = List.of(john1, kate1, john2, nancy1, nancy2);
        Map<String, List<Person>> result = persons.stream().collect(Collectors.groupingBy(Person::getName));
        System.out.println(result);
    }
}

How can I get Stream<List<Person>> instead Map<String, List<Person>> into result? and don't need keys. Can I get it without Map-collection using?

UPD: There are persons with the same name in every list

1

There are 1 answers

2
Nowhere Man On BEST ANSWER

Upon building the map, return the stream for the Collection<List<Person>> retrieved by Map::values method:

Stream<List<Person>> stream = persons.stream()
        .collect(Collectors.groupingBy(Person::getName))
        .values() // Collection<List<Person>>
        .stream(); // Stream<List<Person>>