为什么我无法使用 .forEach() 打印对象?

Dan*_*anE 0 java list stream

我正在尝试使用流按国籍对我的对象进行分组并将其打印出来。
但它说:“无法解析方法'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)

Era*_*ran 5

.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)