Maxim Rong
Maxim Rong

Reputation: 125

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

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?

Upvotes: 2

Views: 1083

Answers (1)

Andreas
Andreas

Reputation: 159135

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

Upvotes: 4

Related Questions