person : persons) { List<Integer> ages = agesBySex.get(person.sex()); if (ages == null) { ages = new ArrayList<>(); agesBySex.put(person.sex(), ages); } ages.add(person.age()); } Map<Sex, Double> averageAgeBySex = new HashMap<>(); for (Map.Entry<Sex, List<Integer>> entry : agesBySex.entrySet()) { double sum = 0; for (Integer age : entry.getValue()) { sum += age; } averageAgeBySex.put(entry.getKey(), sum / (double) entry.getValue().size()); } Map<Sex, Double> averageAgeBySex = persons.stream() .collect( Collectors.groupingBy( Person::sex, Collectors.averagingDouble(Person::age) ) );