What is the best way to transform and filter a Java Map using streams efficiently?

Another approach is using Collectors.filtering(), which allows filtering within the collector itself:

Map<String, Integer> output = input.entrySet().stream()
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                e -> Integer.parseInt(e.getValue()),
                (v1, v2) -> v1, // Merge function (not needed here)
                () -> new HashMap<>()
        ));
output.entrySet().removeIf(e -> e.getValue() % 2 != 0); // Remove odd values after collection

Why this works:

  • We first convert everything and collect into a HashMap.
  • Then we remove odd values after collecting, which can be useful in cases where filtering before collecting isn’t feasible.