简体   繁体   中英

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?

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

If you are interested in returning a map, you could use the following:

public static <K, V> Map<K, V> filterByKeys(final Map<K, V> map, final Iterable<K> keys) {
    final Map<K, V> newMap = new HashMap<>();
    keys.forEach(key -> Optional.ofNullable(map.get(key))
            .ifPresent(value -> newMap.put(key, value)));
    return newMap;
}

Correct this :

List<Long> coolPeople = new ArrayList();

and for the other part :

List<Person> coolPersons=new ArrayList<Person>();
for (Long id:coolPeople) {
     Person p=map.get(id);
     coolPersons.add(p);
}

Feel free to comment if you are having any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM