Transform and filter a Java Map with streams

前端 未结 6 1692
既然无缘
既然无缘 2021-01-31 02:40

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         


        
6条回答
  •  一生所求
    2021-01-31 03:36

    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.

提交回复
热议问题