americanheartbreak americanheartbreak - 1 month ago 15
Java Question

partial search collections java

I am trying to write code in Java for a mp3 class. I wish to be able to complete a full or partial search on the title and artist and it will display on the songs containing the partial string.

This is the code I have written so far.. it will only work in a tester if the user enters the full title or full artist name:

Class code

public void searchByArtist(String artist){
for(Song s : songs){
if(s.getArtist().equalsIgnoreCase(artist)){
System.out.println(s.toString());
}
}

//search for a song by title

public void searchByTitle(String title){
for(Song s : songs){
if(s.getTitle().equalsIgnoreCase(title)){
System.out.println(s.toString());
}
}
}


Tester code

case 4:
keyIn.nextLine(); //clear the buffer of the previous option
System.out.println();
System.out.print("Please enter Title: ");
title = keyIn.nextLine();
player.searchByTitle(title);
break;

case 5:
keyIn.nextLine(); //clear the buffer of the previous option
System.out.println();
System.out.print("Please enter Artist: ");
artist = keyIn.nextLine();
player.searchByArtist(artist);
break;

Answer

To match partially and in a case insensitive way, a simple way is to replace equalsIgnoreCase with toLowerCase() and then contains, for example:

String search = artist.toLowerCase();
for (Song s : songs) {
    if (s.getArtist().toLowerCase().contains(search)) {
        System.out.println(s.toString());
    }
}

Note that toLowerCase() is locale specific. If the titles are not in the default locale, then make sure to specify the appropriate Locale as a parameter.