Filtering a map based on a list of keys
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());
An alternative solution (and possibly more efficient - depending on the size of the map / list) would be to copy the map and act on the keySet
directly:
Map<Long, Person> copy = new HashMap<> (personMap);
copy.keySet().retainAll(coolPeople);
Collection<Person> result = copy.values();