I think you can use FlatMap:
List<Song> songs = service.getSongs();
List<ArtistWithSongs> artistWithSongsList = songs.stream()
.collect(Collectors
.groupingBy(s -> s.getArtist(), Collectors.toList()))
.entrySet()
.flatMap(as -> new ArtistWithSongs(as.getKey(), as.getValue()))
.collect(Collectors.toList());
Edit:
Sorry, we cannot use flatMap after collect () because it does not return a stream. Another solution:
List<ArtistWithSongs> artistWithSongsList = new ArrayList<>();
songs.stream()
.collect(Collectors.groupingBy(Song::getArtist))
.forEach((artist, songs) -> artistWithSongsList.add(new ArtistWithSongs(artist, songs)););
source
share