Transform and filter a Java Map with streams

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

    Yes, you can map each entry to another temporary entry that will hold the key and the parsed integer value. Then you can filter each entry based on their value.

    Map output =
        input.entrySet()
             .stream()
             .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), Integer.valueOf(e.getValue())))
             .filter(e -> e.getValue() % 2 == 0)
             .collect(Collectors.toMap(
                 Map.Entry::getKey,
                 Map.Entry::getValue
             ));
    

    Note that I used Integer.valueOf instead of parseInt since we actually want a boxed int.


    If you have the luxury to use the StreamEx library, you can do it quite simply:

    Map output =
        EntryStream.of(input).mapValues(Integer::valueOf).filterValues(v -> v % 2 == 0).toMap();
    

提交回复
热议问题