Search code examples
java-8java-streamcollectors

Filter Map keys into a set


I have a map Map<String,EnrollmentData> which maps student ID to his data.
The student id need to be filtered on certain EnrollmentData attributes ,and returned as a Set.

Map<String, EnrollmentData> studentData = .........;
if(MapUtils.isNotEmpty(studentData )){
        Set<String> idSet = studentData .entrySet().stream()
                     .filter(x -> x.getValue().equals(...) )
                     .collect(Collectors.toSet( x -> x.getKey()));
}

However,this gives me a compilation error in the toSet [ Collectors is not applicable for the arguments (( x) -> {}) ] .
What needs to be done here.


Solution

  • After the filtering, you have a Stream<Map.Entry<String, EnrollmentData>>. Collecting with toSet() (which accepts no arguments) would collect Entry<String, EnrollmentData>s, but you want to map each element to their key prior to collecting instead.

    You must first map the elements of the resulting stream to the Entry's key:

    .filter(yourFilterFunction)
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());