Home > Software design >  Why I can't print objects with .forEach()?
Why I can't print objects with .forEach()?

Time:12-27

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);
    }

CodePudding user response:

.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 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));
  • Related