Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting values in a map

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?

like image 477
IUnknown Avatar asked Dec 02 '25 10:12

IUnknown


1 Answers

You may do it like so,

Map<String, Long> studentPerCity = students.values().stream().filter(StudentData::isCurrent)
        .collect(Collectors.groupingBy(StudentData::getCity, Collectors.counting()));
like image 132
Ravindra Ranwala Avatar answered Dec 04 '25 22:12

Ravindra Ranwala