Java 8 stream, obtain average age by country

Viewed 796

I'm trying to get into functional programming on java 8

User class

public class User {
    private String name;
    private Country country;
    private int age;
    // setters - getters
}

Country class

public class Country {
    private String name;
    private int population;
    //setters - getters
}

Now I want to get the average age of Users by Country, basically a Map<String, Double>. I can do it the old way just by iterating the users list. However I would like to implement it in a functional way , with stream. I know about collect and groupingBy.

I tried users.stream().collect(Collectors.groupingBy(user -> user.getCountry())); and get a Map<String, List<User>>. Can't figure out how to do the averaging part.

1 Answers
Related