2

我正在尝试获取 type 的地图A -> A,并将其分组为A to List<A>. (也颠倒了键值关系,但我认为这不一定相关)。

这就是我现在所拥有的:

private static Map<Thing, List<Thing>> consolidateMap(Map<Thing, Thing> releasedToDraft) {

    // Map each draft Thing back to the list of released Things (embedded in entries)
    Map<Thing, List<Map.Entry<Thing, Thing>>> draftToEntry = releasedToDraft.entrySet().stream()
            .collect(groupingBy(
                    Map.Entry::getValue,
                    toList()
            ));

    // Get us back to the map we want (Thing to list of Things)
    return draftToEntry.entrySet().stream()
            .collect(toMap(
                    Map.Entry::getKey,
                    ThingReleaseUtil::entriesToThings
            ));
}

private static List<Thing> entriesToThings(Map.Entry<Thing, List<Map.Entry<Thing, Thing>>> entry) {
    return entry.getValue().stream()
            .map(Map.Entry::getKey)
            .collect(toList());
}

我想在单个语句中执行此操作,并且我觉得必须可以将 to 转换Map<Thing, List<Map.Entry<Thing, Thing>>>为操作Map<Thing, List<Thing>>的一部分groupingBy

我试过使用reducing()自定义收集器,我能找到的一切;但由于缺乏复杂的示例,以及我能找到的少数类似示例List.of()在 Java 8 中不存在(Collections.singletonList()似乎不是一个好的替代品),我感到很困难。

有人可以帮我解决可能很明显的问题吗?

4

1 回答 1

5

必须在线

private static Map<Thing, List<Thing>> consolidateMap(Map<Thing, Thing> releasedToDraft) {
        return releasedToDraft.entrySet().stream()
                .collect(groupingBy(
                        Map.Entry::getValue,
                        mapping(Map.Entry::getKey, toList())
                ));
    }
于 2019-12-11T00:49:05.290 回答