Use parallelStream foreach to create HashMap, But

2019-02-27 20: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))