Sunil Kumar Naik Sunil Kumar Naik - 1 month ago 12
Java Question

How can I use Collectors instead of manually putting into ConcurrentHashMap in java 8

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.

Answer

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()));
Comments