WE have a map Students { studentId : StudentData }.
StudentData is a POJO with student attributes .
The requirement is to get all students with attribute isCurrent==true.
If so,then extract the city attribute for the student.
This will used to increment the count of a studentpercity map { city : count }
Students.entrySet()
.stream()
.filter(x -> true == x.getValue().isCurrent())
.forEach(x -> {
studentpercity(x.getValue().getCity(), (studentpercity.getOrDefault(x.getValue().getCity(), 0) + 1));
});
Th final output will be a map of city to count of 'current' students.
Is there a more efficient way of achieving this?
You may do it like so,
Map<String, Long> studentPerCity = students.values().stream().filter(StudentData::isCurrent)
.collect(Collectors.groupingBy(StudentData::getCity, Collectors.counting()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With