IUnknown
IUnknown

Reputation: 9809

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.

Upvotes: 0

Views: 503

Answers (1)

MC Emperor
MC Emperor

Reputation: 22977

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());

Upvotes: 2

Related Questions