为什么我不能用 .forEach() 打印对象?
Why I can't print objects with .forEach()?
我正在尝试使用流按国籍对我的对象进行分组并打印出来。
但它说:“无法解析方法‘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);
}
.collect(Collectors.groupingBy(Person::getNationality))
是returns一个Map<String,List<Person>>
.
的终端操作
Map
的 forEach
需要一个 BiConsumer<? super K, ? super V> action
参数,这需要一个有两个参数的方法。这不符合 System.out::println
的签名(所有 println
方法都有一个参数)。
你可以改变
.forEach(System.out::println);
到
.forEach((key,value)->System.out.println (key + ":" + value));
我正在尝试使用流按国籍对我的对象进行分组并打印出来。
但它说:“无法解析方法‘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);
}
.collect(Collectors.groupingBy(Person::getNationality))
是returns一个Map<String,List<Person>>
.
Map
的 forEach
需要一个 BiConsumer<? super K, ? super V> action
参数,这需要一个有两个参数的方法。这不符合 System.out::println
的签名(所有 println
方法都有一个参数)。
你可以改变
.forEach(System.out::println);
到
.forEach((key,value)->System.out.println (key + ":" + value));