简体   繁体   English

带有嵌套HashMap的Java并行流

[英]Java parallel stream with nested HashMap

Given the nested HashMap HashMap<Integer,HashMap<Integer,BigDecimal>> is it possible to set to zero inner HashMap values with parallel streams with acceptable side-effects and respecting non-interference rules? 给定嵌套的HashMap HashMap<Integer,HashMap<Integer,BigDecimal>>是否可以将具有并行流且具有可接受的副作用并遵守无干扰规则的内部HashMap值设置为零?

For example,given HashMap: 例如,给定HashMap:

HashMap<Integer,HashMap<Integer,BigDecimal>> myMap = null;

is the final forEach in: 是最后的forEach:

myMap.entrySet().parallelStream().forEach(e -> {
            e.getValue().entrySet().parallelStream().forEach(e1 -> {
                e1.setValue(new BigDecimal(0));
                });
        });

acceptable side-effects and respecting non-interference rules? 可接受的副作用并遵守无干扰规则?

... is it possible to set to zero inner HashMap values with parallel streams... ...可以将并行流的内部HashMap值设置为零...

It seems it works, however HashMap is not the thread-safe implementation so I discourage you from using this way. 似乎HashMap ,但是HashMap不是线程安全的实现,因此我不鼓励您使用这种方式。

... with acceptable side-effects and respecting non-interference rules? ...具有可接受的副作用并遵守无干扰规则?

Your usage of Stream::for has side-effects since it changes the source of the Stream. Stream::for用法具有副作用,因为它更改了Stream的来源。 I recommend you to use Stream::map and collecting the structure back to Map afterward using one parrallelStream : 我建议您使用Stream::map ,然后使用一个parrallelStream将结构收集回Map

Map<Integer, Map<Integer,BigDecimal>> myMap2 = myMap.entrySet().parallelStream()
    .map(e -> new AbstractMap.SimpleEntry<>(
        e.getKey(), 
        e.getValue().entrySet().stream()
                               .collect(Collectors.toMap(Entry::getKey, i -> BigDecimal.ZERO))))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

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

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