Java 8 groupingBy, Filter entries for fields larger than average

Trying to learn java 8 GroupingBy Country I'm trying to filter records (people) that are above average age (Collection) by returning a list of people who meet these criteria.

So the equivalent of SQL

SELECT * FROM PERSON, AVG(AGE) AS AVG_AGE
GROUPBY COUNTRY
WHERE AGE > AVG_AGE

This is my attempt so far that has only half occupied me.

personStream.collect(
            Collectors.groupingBy(
                    p -> p.getCountry(),
                    Collectors.averagingInt(p -> p.getAge)))

So far, this has returned to me only a card with a classifier as a key and the country's average age as a value.

Chan, Japan, 40
Chong, Japan, 20
Amy, Japan, 37
James, UK, 25
Abby, UK, 15,
Jean, France 15
Pierre, France, 50

Average Japanese age = 32.33
Average UK age = 20
Average French age = 32.5

ResultSet
Chan, Japan, 40
Chong, Japan, 20
Amy, Japan, 37
James, UK, 25
Pierre, France, 50

Any advice would be appreciated.

+4
source share
2 answers

. 2 : , .

, SQL-, , : WHERE.

, . , persons.

Map<String, Double> map =
        persons.stream().collect(
            groupingBy(
                p -> p.getCountry(),
                averagingInt(p -> p.getAge())
            )
        );

persons.stream().filter(p -> p.getAge() > map.get(p.getCountry())).collect(toList());
+6

, .filter(p → p.getAge() > averageAge), - averageAge , .

0

Source: https://habr.com/ru/post/1616506/


All Articles