简体   繁体   中英

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.

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

We can do this as follows also:

results.stream()
       .flatMap(res -> res.getSeries().stream())
       .flatMap(series -> series.getValues().stream())
       .collect(Collectors.toMap(
                              vals -> vals.get(1).toString(),
                              vals -> vals.get(2).toString(),
                              (vals1,vals2) -> vals2,
                              ConcurrentHashMap::new);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM