I have a Java Map that I\'d like to transform and filter. As a trivial example, suppose I want to convert all values to Integers then remove the odd entries.
Map
You could use the Stream.collect(supplier, accumulator, combiner) method to transform the entries and conditionally accumulate them:
Map even = input.entrySet().stream().collect(
HashMap::new,
(m, e) -> Optional.ofNullable(e)
.map(Map.Entry::getValue)
.map(Integer::valueOf)
.filter(i -> i % 2 == 0)
.ifPresent(i -> m.put(e.getKey(), i)),
Map::putAll);
System.out.println(even); // {a=1234, c=3456}
Here, inside the accumulator, I'm using Optional
methods to apply both the transformation and the predicate, and, if the optional value is still present, I'm adding it to the map being collected.