有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用parallelStream foreach创建HashMap,但有时值为空

Java代码如下:

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
    });

我猜这是因为HashMap是线程不安全的,所以我用Hashtable代替它。然后它运行正常,所有的值都有值,但我不知道为什么


共 (1) 个答案

  1. # 1 楼答案

    HashMap不是线程安全的,所以不要使用并行流

    再说,既然溪流能为你做这件事,为什么还要在那里做呢

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