简体   繁体   English

如何“卷积”两个流

[英]How to "convolut" two streams

I'm a newbie in streams, but really fascinating by functional programming.我是流的新手,但对函数式编程非常着迷。 I would like to "concat" two maps (ie dictonaries) Map<Character, Double> map1 and Map<Character, Double> map2 having the same key-sets (the set of chars) in such a way that results in the third map Map<Character, Double> map3 that have the set of keys the same as the previous two, and the values equal to differences of appropriate values from map1 and map2 .我想“连接”两张地图(即字典) Map<Character, Double> map1Map<Character, Double> map2具有相同的键集(字符集),从而导致第三张地图Map<Character, Double> map3具有与前两个相同的键集,并且值等于map1map2的适当值的差异。 Could you please help?能否请你帮忙? How to obtain the result by means of streams?如何通过流的方式获取结果?

This solution might be helpful.此解决方案可能会有所帮助。

    Map<Character, Double> map1 = new HashMap<>();
    map1.put('A', 23.0);
    map1.put('B', 50.0);

    Map<Character, Double> map2 = new HashMap<>();
    map2.put('A', 15.0);
    map2.put('B', 40.0);

    //method 1 : Result stored in third map
    Map<Character, Double> map3 = new HashMap<>();
    map1.keySet().forEach(key -> map3.put(key, map1.get(key) - map2.get(key)));

    //method 2 : using collectors
    Map<Character, Double> map4 = map1.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue() - map2.get(entry.getKey())));

    //method 3 : Result stored in map1
    map2.forEach((key, val) -> map1.merge(key, val, (val1, val2) -> val1 - val2));

    System.out.println("map1 = " + map1);
    System.out.println("map3 = " + map3);
    System.out.println("map4 = " + map4);

Refer Lambda expression java docs for better understanding.请参阅Lambda 表达式 java 文档以获得更好的理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM