Java 收集返回顶级项目的嵌套地图流

Java collect nested stream of maps returning top level items

我有以下型号:

class Item {
    String name;
    ...
    List<SubItem> subItems;
}

class SubItem {
    String name;
    ...
    List<String> ids;
}

对于 subItem.ids 中的每个 id,我想提取一些顶级参数。为此,我定义了一个自定义元组:

class AdditionalParams {
    private final String itemName;
    private final String subItemName;
    ...
}

目标是 return 一个 Map<String, AdditionalParams> 其中:

我假设 ID 是唯一的,因此在向地图添加元素时不会发生任何冲突。

我的解决方案

我尝试将 flatMapCollectors.toMap 一起使用:

List<Item> allItems = ...
Map<String, AdditionalParams> result = allItems
    .stream()
    .flatMap(i -> i.getSubItems()
                   .stream()
                   .map(si -> si.getIds()
                                .stream()
                                .collect(
                                    Collectors.toMap(
                                        Function.identity(),
                                        id -> new AdditionalParams(i.getName(), si.getName())
                                    )
                                )
                   )
    )  // Stream< Map<String, AdditionalParams> >
    .collect(
        Collectors.toMap(m -> m.getKey(), m -> m.getValue())
    )

问题是最后一行 (.collect(Collectors.toMap(...) 不起作用(或者我做错了)。我试着遵循这个答案 但也无法使其工作。

我的方法做错了什么?如何获得 Map<String, AdditionalParams> 类型的结果?

解决这个问题的方法是将中间状态映射到映射的条目,然后收集它们。这会像 --

Map<String, AdditionalParams> result = allItems
        .stream()
        .flatMap(item -> item.getSubItems().stream()
                .flatMap(subItem -> subItem.getIds()
                        .stream()
                        .map(id -> new AbstractMap.SimpleEntry<>(
                                id, new AdditionalParams(item.getName(),
                                subItem.getName())))))
        .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
                AbstractMap.SimpleEntry::getValue));