假設我們要實現這些類:
public static class Song
{
String title;
Artist artist;
Album album;
Song(String title, Artist artist, Album album)
{ this.title = title; this.artist = artist; this.album = album; }
@Override public String toString() { return "Song: " + title; }
}
public static class Artist
{
String name;
Artist(String name) { this.name = name; }
@Override public String toString() { return "Artist: " + name; }
}
public static class Album
{
String name;
Album(String name) { this.name = name; }
@Override public String toString() { return "Album: " + name; }
}
其中:
Song
就是你現在用相當不幸的名稱SongInfo
Artist
調用是一個類,你還沒有,但你應該。如果你不能處理這個問題,那麼只要你看到Artist
就想到一個String
,裏面有一個藝術家的名字。
Album
是另一類,你還沒有,但你應該。如果您無法處理該問題,那麼無論何時您看到Album
只需考慮一個String
並附上相冊的標題即可。
並假設我們開始與這個數據集:
Artist artist1 = new Artist("Artist1");
Artist artist2 = new Artist("Artist2");
Set<Artist> artists = new HashSet<>(Arrays.asList(artist1, artist2));
Album album1 = new Album("Album1");
Album album2 = new Album("Album2");
Set<Album> albums = new HashSet<>(Arrays.asList(album1, album2));
Song song11a = new Song("Song11a", artist1, album1);
Song song11b = new Song("Song11b", artist1, album1);
Song song22a = new Song("Song22a", artist2, album2);
Song song22b = new Song("Song22b", artist2, album2);
List<Song> songs = Arrays.asList(song11a, song11b, song22a, song22b);
那麼下面會給你想要的東西:
Collection<Song> getSongsByArtist(Collection<Song> songs, Artist artist)
{
return songs.stream().filter(song -> song.artist == artist)
.collect(Collectors.toList());
}
Collection<Album> getAlbumsByArtist(Collection<Song> songs, Artist artist)
{
return songs.stream().filter(song -> song.artist == artist)
.map(song -> song.album).collect(Collectors.toSet());
}
和下面會給你你一直想知道的一切關於您的數據集,但不敢問:
Map<Song,Artist> artistsBySong = songs.stream()
.collect(Collectors.toMap(Function.identity(), song -> song.artist));
Map<Song,Album> albumsBySong = songs.stream()
.collect(Collectors.toMap(Function.identity(), song -> song.album));
Map<Artist,List<Song>> songsByArtist = songs.stream()
.collect(Collectors.groupingBy(song -> song.artist));
Map<Album,List<Song>> songsByAlbum = songs.stream()
.collect(Collectors.groupingBy(song -> song.album));
assert songs.stream().map(song -> song.album)
.collect(Collectors.toSet()).equals(albums);
assert songsByAlbum.keySet().equals(albums);
「器官將這些數據分成3個不同的片段,例如:藝術家列表 - >所選藝術家的專輯 - >所選專輯的歌曲。「如果你能夠在一個句子的片段中解釋你在想什麼奇怪的想法給許多不知名的人,這不是很好嗎?但我恐怕這隻對你有意義。 –
@MikeNakis我添加了更多信息,希望它有道理。請讓我知道你是否有任何其他懷疑理解這個問題。 – Shubham
創建一個'歌曲'類,它有一個'List'(名爲'infos'?)和一個'List'類,它有一個'List '(名爲'songs'?)。 –
2017-02-26 19:46:15