Search code examples
javacollectionsjava-8java-stream

Filtering a map based on a list of keys


I have a map like the following:

class Person {

    Long personId;
    String name;

    /*Getters and Setters*/
}

I have populated a map Map<Long, Person> personMap = new HashMap<>();

The key of the map is the personId itself. I have a list of personIds like so,

List<Long> coolPeople = new ArrayList<>();

now I want to iterate through the map and get all the values with the keys corresponding the ids in the list coolPeople, and then store it in a List.

How can I achieve this in Java 8 optimally?


Solution

  • It would be more efficient to iterate over the identifiers of the List and look them up in the Map, since search by key in a HashMap takes expected O(1) time, while the search in the List can take O(n) time at the worst case.

    List<Person> people = 
        coolPeople.stream()
                  .map(id -> personMap.get(id)) // or map(personMap::get)
                  .filter(Objects::nonNull)
                  .collect(Collectors.toList());