使用Java 8流反转Map结构 [英] Reverse Map structure using Java 8 streams

查看:1734
本文介绍了使用Java 8流反转Map结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个类

public class MyClass {
    public int langId;
    public int sectionId;
}

如果我有一个地图将LangId映射到MyClass的所有实例有这个LangId:

If I have a map that maps a LangId to all the instances of MyClass that have that LangId:

Map<Integer, List<MyClass>> mapLangIdToListOfMyClass = new HashMap<>();

使用Java 8流,是否有一种简单的方法来使用前一个Map并创建一个新的Map将SectionId映射到具有SectionId的MyClass的所有实例:

Using Java 8 streams, would there be a simple way to consume the previous Map and create a new Map that maps SectionId to all the instances of MyClass that has that SectionId:

Map<Integer, List<MyClass>> mapSectionIdToListOfMyClass = new HashMap<>();


推荐答案

我认为你可以做到

Map<Integer, List<MyClass>> mapSectionIdToListOfMyClass = mapLangIdToListOfMyClass
                               .values()
                               .stream()
                               .flatMap(List::stream)
                               .collect(Collectors.groupingBy(j -> j.sectionId));

这篇关于使用Java 8流反转Map结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆