如何将 Stream<Person> 分组到 Stream<List<Person>> 中,而不是分组到 Map<String, <List<Person>> 中?
How can I group Stream<Person> into Stream<List<Person>>, not into Map<String, <List<Person>>?
我有 POJO class:
@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<String, List<Person>>
变成 result
?而且不需要钥匙。不使用Map-collection可以获取吗?
更新:每个列表中都有同名的人
构建地图后,return Collection<List<Person>>
的流通过 Map::values
方法检索:
Stream<List<Person>> stream = persons.stream()
.collect(Collectors.groupingBy(Person::getName))
.values() // Collection<List<Person>>
.stream(); // Stream<List<Person>>
我有 POJO class:
@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<String, List<Person>>
变成 result
?而且不需要钥匙。不使用Map-collection可以获取吗?
更新:每个列表中都有同名的人
构建地图后,return Collection<List<Person>>
的流通过 Map::values
方法检索:
Stream<List<Person>> stream = persons.stream()
.collect(Collectors.groupingBy(Person::getName))
.values() // Collection<List<Person>>
.stream(); // Stream<List<Person>>