gpt4 book ai didi

java - 使用 Stream 映射 Collection 结果

转载 作者:搜寻专家 更新时间:2023-11-01 02:58:59 27 4
gpt4 key购买 nike

我正在尝试想出一种无需调用 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;
}
}

是否有更优化的方法?

最佳答案

我认为在这种情况下使用 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)););

关于java - 使用 Stream 映射 Collection 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946731/

27 4 0