我试图想办法在不调用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;
}
}
有更优化的方法吗?
答案 0 :(得分:2)
我认为在这种情况下使用forEach就足够了:
List<ArtistWithSongs> artistWithSongsList = new ArrayList<>();
service.getSongs().stream()
.collect(Collectors.groupingBy(s -> s.getArtist(), Collectors.toList()))
.entrySet()
.forEach((k, v) -> artistWithSongsList.add(new ArtistWithSongs(k, v)););
答案 1 :(得分:1)
我认为你可以使用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)););