简体   繁体   English

使用 java 8 中的列表值迭代 map

[英]Iterate over a map with values as List in java 8

Iterate over a Map<Integer, List<String>> and convert to type List<KeyPair> .遍历Map<Integer, List<String>>并转换为List<KeyPair>类型。 Any better way to do it in java 8 (Using streams).在 java 8(使用流)中有更好的方法。

Naive way:天真的方式:

final List<KeyPair> keyPairs = Lists.newArrayList();
 for (final Map.Entry<Integer, List<String>> entry : map.entrySet()) {
            for (final String value : entry.getValue()) {
                keyPairs.add(new KeyPair()
                .withHashKey(value)
                .withRangeKey(entry.getKey()));
            }
   }

First, iterate over the map entrySet and then you can use flatMap for list of value for the map key and create KeyPair with entry key and every value of list and collect as a list.首先,遍历 map 条目集,然后您可以使用flatMap作为 map 键的值列表,并使用条目键和列表的每个值创建KeyPair并收集为列表。

List<KeyPair> keyPairs = map.entrySet()
       .stream()
       .flatMap(entry -> entry.getValue()
                              .stream()
                              .map(value -> new KeyPair()
                                               .withHashKey(value)
                                               .withRangeKey(entry.getKey())))
       .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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