From 00336f0b5598407cea517b4adfa788232a44d1a0 Mon Sep 17 00:00:00 2001 From: Klagarge Date: Mon, 7 Apr 2025 12:42:53 +0200 Subject: [PATCH] feat: add function to count songs by artist --- src/main/scala/TopSongs/TopSongs.scala | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/main/scala/TopSongs/TopSongs.scala b/src/main/scala/TopSongs/TopSongs.scala index 7907961..465bdcd 100644 --- a/src/main/scala/TopSongs/TopSongs.scala +++ b/src/main/scala/TopSongs/TopSongs.scala @@ -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") + } +