快速问一下,我想将下面的Map<String, Map<String, Integer>>展平为另一个对象。我目前正在做的是在流中嵌入一个流,这是我不太喜欢的,有一种方法可以以线性的方式做到这一点。
this.ourMap.entrySet().stream()
.flatMap(player ->
player.getValue().entrySet().stream()
.map(game -> new TransformedMap("StaticID", player.getKey(), game.getKey(), game.getValue())))
.collect(Collectors.toList());发布于 2015-11-14 11:38:42
使用我的免费StreamEx库,这看起来会更简单:
list = EntryStream.of(this.ourMap)
.flatMapValues(games -> games.entrySet().stream())
.mapKeyValue((player, game) ->
new TransformedMap("StaticID", player, game.getKey(), game.getValue()))
.toList();这里使用了EntryStream类,它扩展了Stream<Map.Entry>并提供了一些额外的方便方法。在内部,它被转换成这样的东西:
list = this.ourMap.entrySet().stream()
.<Entry<String, Entry<String, Integer>>>flatMap(entry -> entry.getValue().entrySet()
.stream().map(e -> new AbstractMap.SimpleImmutableEntry<>(entry.getKey(), e)))
.map(entry ->
new TransformedMap("StaticID", entry.getKey(), entry.getValue().getKey(), entry.getValue().getValue()))
.collect(Collectors.toList());https://stackoverflow.com/questions/33690355
复制相似问题