I'm trying to get an ArrayList (or a Set, or anything similar) of the artists of a List of Songs. Each song has the function getArtists which returns an Array of every artist who is participating in the song.
The goal is to have a List of Artists and every Artist should have a List (or Set, whichever is faster) which contains all the Songs where he participates.
My Code works, but it's rather slow (it needs 5 sec for 1600 songs). How can i speed it up?
My Code
private ArrayList<Artist> getArtistsFromSongs(List<Song> songs)
{
long start = System.currentTimeMillis();
ArrayList<Artist> artists = new ArrayList<>();
for (Song song : songs)
{
String[] artistsStringArray = song.getArtists();
for (String artistString : artistsStringArray)
{
boolean artistAlreadyExists = false;
int heExistsAt = -1;
for (int i = 0; i < artists.size(); i++)
{
if (artists.get(i).name.equals(artistString))
{
artistAlreadyExists = true;
heExistsAt = i;
}
}
if (artistAlreadyExists)
{
artists.get(heExistsAt).songs.add(song);
} else
{
Artist newArtist = new Artist(artistString, new ArrayList<>());
newArtist.songs.add(song);
artists.add(newArtist);
}
}
}
long test = System.currentTimeMillis() - start; //~5500 milliseconds
return artists;
}
The Class
class Artist
{
public final String name;
public final ArrayList<Song> songs;
Artist(String name, ArrayList<Song> songs)
{
this.name = name;
this.songs = songs;
}
}
Thanks in advance.