4

Given a class

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

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<>();

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<>();
HLP
  • 2,142
  • 5
  • 19
  • 20

1 Answers1

6

I think you can do

Map<Integer, List<MyClass>> mapSectionIdToListOfMyClass = mapLangIdToListOfMyClass
                               .values()
                               .stream()
                               .flatMap(List::stream)
                               .collect(Collectors.groupingBy(j -> j.sectionId));
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116