How can I Use Collectors to collect in a ConcurrentHashMap instread of putting manually into ConcurrentHashMap
ConcurrentHashMap<String, String> configurationMap = new ConcurrentHashMap<>();
List<Result> results = result.getResults();
results.stream().forEach(res -> {
res.getSeries().stream().forEach(series -> {
series.getValues().stream().forEach(vals ->{
configurationMap.put(vals.get(1).toString(),vals.get(2).toString());
});
});
});
//Note: vals is List<List<Object>> type
Help will be appreciated.
synchronizedMap() requires each thread to acquire a lock on the entire object for both read/write operations. By comparison, the ConcurrentHashMap allows threads to acquire locks on separate segments of the collection, and make modifications at the same time.
To insert mappings into a ConcurrentHashMap, we can use put() or putAll() methods. The below example code explains these two methods.
collect() is one of the Java 8's Stream API's terminal methods. It allows us to perform mutable fold operations (repackaging elements to some data structures and applying some additional logic, concatenating them, etc.) on data elements held in a Stream instance.
You can use Collectors.toConcurrentMap
results.stream()
.flatMap(res -> res.getSeries().stream())
.flatMap(series -> series.getValues().stream())
.collect(Collectors.toConcurrentMap(
vals -> vals.get(1).toString(),
vals -> vals.get(2).toString()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With