简体   繁体   中英

Why I can't print objects with .forEach()?

I am trying to use streams to group my objects by nationality and print them out.
But it says: "Cannot resolve method '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)) is a terminal operation that returns a Map<String,List<Person>> .

Map 's forEach requires a BiConsumer<? super K, ? super V> action BiConsumer<? super K, ? super V> action BiConsumer<? super K, ? super V> action argument, which requires a method with two arguments. This doesn't conform with the signature of System.out::println (all the println methods have a single argument).

You could change

.forEach(System.out::println);

to

.forEach((key,value)->System.out.println (key + ":" + value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM