feat: add function to count songs by artist

This commit is contained in:
Rémi Heredero 2025-04-07 12:42:53 +02:00
parent 5b1bd3e135
commit 00336f0b55
Signed by: Klagarge
GPG Key ID: 735B36B074A65F0F

View File

@ -101,6 +101,18 @@ case class TopSongs(songs: List[Song] = List()) {
}
})
}
// This function counts the number of songs by each artist
// It uses flatMap to extract the artist names from the songs
// Then it groups the songs by artist name and counts the occurrences
// Finally, it returns a map with the artist names as keys and the counts as values
def countSongsByArtist(songs: List[Song]): Map[String, Int] = {
songs.flatMap(_.singer.map(_.person.name))
.groupBy(identity)
.view.mapValues(_.size)
.toMap
}
}
@main def main(): Unit =
@ -137,3 +149,13 @@ case class TopSongs(songs: List[Song] = List()) {
// print the songs
topSongs.printSongs()
println("----------");
// print the number of songs by artist
val songsByArtist = topSongs.countSongsByArtist(topSongs.songs)
println("Number of songs by artist:")
songsByArtist.foreach {
case (artist, count) => println(s"$artist: $count")
}