java - 使用 Java 8 Streams 将 Map 的 Map 转换为 Lists

我有一张 map :

Map<String, Map<Integer, List<Integer>>>
e.g. Map<Name, Map<Id, List<ReferenceId>>>

Outcome:
List<Id>
List<ReferenceId>

我想将此 map 转换为两个整数列表。一个列表包含内部映射键,另一个包含内部映射值(即 List<Integer> )

谁能告诉我如何使用流在 Java 8 中做到这一点?

我尝试过这种方式,但得到了 Cast Exception,无法将 String 转换为 Integer。
map.values().stream()
    .map(m -> m.entrySet()
    .stream()
    .map(e -> e.getKey())
    .collect(Collectors.toList()))
    .flatMap(l -> l.stream())
    .collect(Collectors.toList());

最佳答案

Map<String, Map<Integer, List<Integer>>> map = ...

List<Integer> keys = map.values()       // Collection<Map<Integer, List<Integer>>>
        .stream()                       // Stream<Map<Integer, List<Integer>>>
        .map(Map::keySet)               // Stream<Set<Integer>>
        .flatMap(Set::stream)           // Stream<Integer>
        .collect(Collectors.toList());  // List<Integer>

List<Integer> values = map.values()     // Collection<Map<Integer, List<Integer>>>
        .stream()                       // Stream<Map<Integer, List<Integer>>>
        .map(Map::values)               // Stream<Collection<List<Integer>>>
        .flatMap(Collection::stream)    // Stream<List<Integer>>
        .flatMap(List::stream)          // Stream<Integer>
        .collect(Collectors.toList());  // List<Integer>

https://stackoverflow.com/questions/38360276/

相关文章:

r - 每种可能组合的 Wilcoxon 秩和检验

junit4 - Wiremock 模拟返回 HTTP 500

r - 交叉比较相同数据框的列

r - 从 R 中的公式中提取模型框架时排除变量

atom-editor - 原子氢 : How is "run cell" used?

persistence - 在 Quartz 调度程序中看到异常导致作业无法运行

java - 如果单例不好!为什么spring bean默认是单调的

r - 为列名传递变量?

docker - 在 alpine 容器中使用 confluent-kafka python 客户端

r - R中的双重居中