I want to learn how to use the Java 8 syntax with streams and got a bit stuck.
It's easy enough to groupingBy when you have one key for every value. But what if I have a List of keys for every value and still want to categorise them with groupingBy? Do I have to break it into several statements or is there possibly a little stream magic that can be done to make it simpler.
This is the basic code:
List<Album> albums = new ArrayList<>();
Map<Artist, List<Album>> map = albums.stream().collect(Collectors.groupingBy(this::getArtist));
It works great if there is only one Artist for every Album. But I must return a List since an Album can have many Artists. Album and Artist are used for illustration of course, I have real-world types..
There's probably a simple solution but I haven't found it in a while so I'm calling on the collective brain this site represents to solve it. :) A complex solution is also welcome in case a simple one doesn't exist.
In Album class or as an utility method taking an Album as argument:
Artist getArtist(); // ok
List<Artist> getArtist(); // Not ok, since we now have many "keys" for every Album
Cheers, Mikael Grev