In: Computer Science
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song titles by classifying them according to genre (e.g., Pop, Rock, etc.). The class uses a HashMap to map a genre with a set of songs that belong to such a genre. The set of songs will be represented using a HashSet. Your driver output should sufficiently prove that your code properly implements the code below.
public class SongsDatabase {
private Map<String, Set<String>> genreMap =
new HashMap<String, Set<String>>();
public void addSong(String genre, String songTitle) {
// You must implement this method
}
public Set<String> getSongs(String genre) {
// You must implement this method
}
public String getGenreOfSong(String songTitle) {
// You must implement this method
}
}
So, your hashMap, visually, looks like the following:
Soul -> (SoulSong1, SoulSong2, SoulSong3, etc.)
Rock -> (RockSong1, RockSong2, RockSong3, etc.)
Jazz -> (JazzSong1, JazzSong2, JazzSong3, etc.)
Code:
import java.util.*;
public class SongsDatabase {
private Map<String, Set<String>> genreMap = new HashMap<String, Set<String>>();
public void addSong(String genre, String songTitle) {
// You must implement this method
if(genreMap.containsKey(genre)){
genreMap.get(genre).add(songTitle);//adding songTitle with genre
}else{
//making a new set when the genre does not exist and adding it to the hashmap
Set<String> newSet = new HashSet<String>();
newSet.add(songTitle);
genreMap.put(genre,newSet);
}
}
public Set<String> getSongs(String genre) {
// You must implement this method
return genreMap.get(genre);//returning the set corresponding to the genre
}
public String getGenreOfSong(String songTitle) {
// You must implement this method
for (Map.Entry<String, Set<String>> entry : genreMap.entrySet()) {
if(entry.getValue().contains(songTitle)){
return entry.getKey();
}
}
return "No value found";
}
public static void main(String args[]){
SongsDatabase db = new SongsDatabase();
//adding songs
db.addSong("Soul","SoulSong1");
db.addSong("Soul","SoulSong2");
db.addSong("Soul","SoulSong3");
db.addSong("Rock","RockSong1");
db.addSong("Rock","RockSong2");
db.addSong("Rock","RockSong3");
db.addSong("Jazz","JazzSong1");
db.addSong("Jazz","JazzSong2");
//getting songs
Set<String> set = db.getSongs("Rock");
Iterator value = set.iterator();
System.out.println("Songs in Rock genre:");
while(value.hasNext()){
System.out.println(value.next());
}
System.out.print("Getting genre of the song SoulSong3 : ");
System.out.println(db.getGenreOfSong("SoulSong3"));
}
}
Output:
Code screenshot: