forked from Klagarge/MSE-AdvProg-MicroProject
		
	feat: add function to count songs by artist
This commit is contained in:
		| @@ -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") | ||||
|   } | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user