Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 476
Sunil Kumar Naik Avatar asked Oct 28 '16 04:10

Sunil Kumar Naik


People also ask

What is the difference between collections SynchronizedMap and ConcurrentHashMap?

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.

Which of the following methods are available in Java Util concurrent Concurrentmap In addition to the methods provided by Java Util map?

To insert mappings into a ConcurrentHashMap, we can use put() or putAll() methods. The below example code explains these two methods.

What is the use of collectors in Java 8?

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.


1 Answers

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()));
like image 73
xiaofeng.li Avatar answered Oct 06 '22 01:10

xiaofeng.li