Java8: HashMap to HashMap using Stream / Map-Reduce / Collector

前端 未结 9 2112
无人及你
无人及你 2020-11-30 18:38

I know how to \"transform\" a simple Java List from Y -> Z, i.e.:

List x;
List y = x.stre         


        
相关标签:
9条回答
  • 2020-11-30 19:01

    Does it absolutely have to be 100% functional and fluent? If not, how about this, which is about as short as it gets:

    Map<String, Integer> output = new HashMap<>();
    input.forEach((k, v) -> output.put(k, Integer.valueOf(v));
    

    (if you can live with the shame and guilt of combining streams with side-effects)

    0 讨论(0)
  • 2020-11-30 19:05

    The declarative and simpler solution would be :

    yourMutableMap.replaceAll((key, val) -> return_value_of_bi_your_function); Nb. be aware your modifying your map state. So this may not be what you want.

    Cheers to : http://www.deadcoderising.com/2017-02-14-java-8-declarative-ways-of-modifying-a-map-using-compute-merge-and-replace/

    0 讨论(0)
  • 2020-11-30 19:06

    A generic solution like so

    public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
            Function<Y, Z> function) {
        return input
                .entrySet()
                .stream()
                .collect(
                        Collectors.toMap((entry) -> entry.getKey(),
                                (entry) -> function.apply(entry.getValue())));
    }
    

    Example

    Map<String, String> input = new HashMap<String, String>();
    input.put("string1", "42");
    input.put("string2", "41");
    Map<String, Integer> output = transform(input,
                (val) -> Integer.parseInt(val));
    
    0 讨论(0)
提交回复
热议问题