我正在尝试一种无需两次调用stream()但无济于事的方法:

List<Song> songs = service.getSongs();

List<ArtistWithSongs> artistWithSongsList = songs.stream()
    .collect(Collectors
        .groupingBy(s -> s.getArtist(), Collectors.toList()))
    .entrySet()
    .stream()
    .map(as -> new ArtistWithSongs(as.getKey(), as.getValue()))
    .collect(Collectors.toList());

按照要求:
class ArtistWithSongs {
    private Artist artist;
    private List<Song> songs;

    ArtistWithSongs(Artist artist, List<Song> songs) {
        this.artist = artist;
        this.songs = songs;
    }
}

有没有更理想的方法?

最佳答案

我认为您可以使用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());

编辑:

抱歉,我们不能在collect()之后使用flatMap,因为它不会返回流。其他解决方案是:
    List<ArtistWithSongs> artistWithSongsList = new ArrayList<>();
    songs.stream()
         .collect(Collectors.groupingBy(Song::getArtist))
         .forEach((artist, songs) -> artistWithSongsList.add(new ArtistWithSongs(artist, songs)););

08-26 09:29