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

后端 未结 2 1431
梦如初夏
梦如初夏 2021-01-12 19:48

How can I Use Collectors to collect in a ConcurrentHashMap instread of putting manually into ConcurrentHashMap

ConcurrentHashMap config         


        
相关标签:
2条回答
  • 2021-01-12 19:55

    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()));
    
    0 讨论(0)
  • 2021-01-12 20:10

    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);
    
    0 讨论(0)
提交回复
热议问题