在Java 8中迭代具有值为列表的映射。

huangapple go评论62阅读模式
英文:

Iterate over a map with values as List in java 8

问题

在Java 8中,可以使用流(streams)来更优雅地执行此操作:

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

这将会迭代Map<Integer, List<String>>并将其转换为List<KeyPair>,更符合Java 8的函数式编程风格。

英文:

Iterate over a Map&lt;Integer, List&lt;String&gt;&gt; and convert to type List&lt;KeyPair&gt;. Any better way to do it in java 8 (Using streams).

Naive way:

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

答案1

得分: 5

首先,迭代地遍历地图的 entrySet,然后您可以使用 flatMap 处理地图键的值列表,并创建 KeyPair,其中包括 entry 键和列表中的每个值,并将其收集为列表。

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

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.

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

huangapple
  • 本文由 发表于 2020年8月4日 12:27:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63240284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定