Use parallelStream foreach to create HashMap, But sometimes value is empty

房东的猫 提交于 2019-12-01 08:07:45

问题


Java Code Like :

List<Detail> DbDetails = ... Like 50000 rows records
Map<Long, List<Detail>> details = new HashMap();

DbDetails .parallelStream().forEach(detail -> {
        Long id = detail.getId();
        details.computeIfAbsent(id, v -> new ArrayList<>()).add(detail);

    });

Then ...

details.entrySet().stream().forEach(e -> {
        e.getValue(); // Some value is empty
    });

I guess it because HashMap is thread-unsafe, so I use Hashtable instead of it. Then it run ok, all value has value, but I don't know why?


回答1:


HashMap is not thread-safe, so don't use parallel streams with it.

Besides, why do that there, when streams can do it for you?

DbDetails.parallelStream().collect(Collectors.groupingBy(Detail::getId))


来源:https://stackoverflow.com/questions/44643621/use-parallelstream-foreach-to-create-hashmap-but-sometimes-value-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!