what is the best way to get a sub HashMap based on a list of Keys?

With Java8 streams, there is a functional (elegant) solution. If keys is the list of keys to keep and map is the source Map.

keys.stream()
    .filter(map::containsKey)
    .collect(Collectors.toMap(Function.identity(), map::get));

Complete example:

    List<Integer> keys = new ArrayList<>();
    keys.add(2);
    keys.add(3);
    keys.add(42); // this key is not in the map

    Map<Integer, String> map = new HashMap<>();
    map.put(1, "foo");
    map.put(2, "bar");
    map.put(3, "fizz");
    map.put(4, "buz");

    Map<Integer, String> res = keys.stream()
        .filter(map::containsKey)
        .collect(Collectors.toMap(Function.identity(), map::get));

    System.out.println(res.toString());

Prints: {2=bar, 3=fizz}

EDIT add a filter for keys that are absent from the map

Leave a Comment