我试图想办法做到这一点,而不必调用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;
}
}
是否有更好的做法呢?
你可以发布你的'ArtistWithSongs'类吗? – shmosel
我怀疑是否可以对流的元素进行分组而不收集它们。 –
没有获得者或接受者?它应该是不可变的吗? – shmosel