0

我有 POJO 类:

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

我有一些可执行代码:

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);
    }
}

我怎样才能Stream<List<Person>>进入?并且不需要钥匙。我可以在不使用 Map-collection 的情况下获得它吗?Map<String, List<Person>>result

UPD:每个列表中都有同名的人

4

1 回答 1

3

构建地图后,返回方法Collection<List<Person>>检索的流Map::values

Stream<List<Person>> stream = persons.stream()
        .collect(Collectors.groupingBy(Person::getName))
        .values() // Collection<List<Person>>
        .stream(); // Stream<List<Person>> 
于 2021-11-23T07:35:19.807 回答