Transform and filter a Java Map with streams

前端 未结 6 1703
既然无缘
既然无缘 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:33

    Guava's your friend:

    Map output = Maps.filterValues(Maps.transformValues(input, Integer::valueOf), i -> i % 2 == 0);
    

    Keep in mind that output is a transformed, filtered view of input. You'll need to make a copy if you want to operate on them independently.

提交回复
热议问题