我正在尝试使用流按国籍对我的对象进行分组并将其打印出来。
但它说:“无法解析方法'println”
class Person {
private String name;
private int age;
private String nationality;
public static void groupByNationality(List<Person> people) {
people
.stream()
.collect(Collectors.groupingBy(Person::getNationality))
.forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)
.collect(Collectors.groupingBy(Person::getNationality))是一个返回 a 的终端操作Map<String,List<Person>>。
Map需要forEach一个BiConsumer<? super K, ? super V> action参数,这需要一个带有两个参数的方法。System.out::println这不符合(所有println方法都有一个参数)的签名。
你可以改变
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
到
.forEach((key,value)->System.out.println (key + ":" + value));
Run Code Online (Sandbox Code Playgroud)