Intersecting List with keys of Map

IUnknown :

We have a map of Student to record Map<Student, StudentRecord>.
Student class is as follows:

Student {
    String id;
    String grade;
    Int age; 
}

Additionally, we have a list of Student Id (List<String>) provided.
Using Java streams, what would be the most efficient way to filter out records of students whose Id exists in the provided list?
The expected outcome is the filtered list mapped against the Id(String) - <Map<Id, StudentRecord>>

Andronicus :

You can stream set of entries:

map.entrySet().stream()
    .filter(e -> list.contains(e.getKey()))
    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

If you also want to map keys to id field, then:

map.entrySet().stream()
    .filter(e -> list.contains(e.getKey()))
    .collect(toMap(e -> e.getKey().getId(), Map.Entry::getValue));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356252&siteId=1