Create albums out of songs I have made a method which returns a list of all songs on my device. Now I want to get a list of albums out of these songs.

What I basically do is go through every song I have in my list, check if its album is already in the list and if not I create a new album. 

This method will take some time since there are 1400 songs on my device so I wondered how I can make this method any faster? Also, any other improvements?

public static ArrayList&lt;Album&gt; loadAlbums( Context c ){
    ArrayList&lt;Song&gt; tmpList = getAllSongs( c);
    ArrayList&lt;Album&gt; albumList = new ArrayList&lt;Album&gt;();

    for( Song s : tmpList ){

        boolean added = false;

        for( Album a : albumList ){

            if( a.getAlbumName().contentEquals( s.getAlbum() ) &amp;&amp; a.getArtistName().contentEquals( s.getArtist() ) ){
                a.addSong( s.getPath() );
                added = true;
            }
        }


        if( !added ){
            Album a = new Album( s.getAlbum() );
            a.setAlbum_id( s.getAlbumId() );
            a.setArtistName( s.getArtist() );
            a.addSong( s.getPath() );

            albumList.add(a);
        }

    }

    tmpList = null;
    return albumList;
}
What you need is a Map. A map is a collection of key --> value combinations. There can not be two equal keys pointing to different values.

There are a few ways to organize this map. The simplest is to make Map&lt;String, Album&gt; albumNames;, but that would make it possible for collisions if two albums had the same album name.

Another alternative is Map&lt;String, List&lt;Album&gt;&gt; for fixing the problem with albums having the same name.

There are more alternatives but they can get quite complex so I think this is enough for now.

Then when you loop through your songs, for each song:


List&lt;Album&gt; possibleAlbums = albumNames.get(song.getAlbum()).

If that returns null, then add a new list and add an album to it.
otherwise loop through the list to find the album you are looking for (that matches the artist). Again, if none is found create a new one.

Once you have found or created a matching album, you can add the song to it.


Other comments:


Declare by interface and not implementation. Make the method return List&lt;Album&gt;, also use for example List&lt;Song&gt; tmpList = getAllSongs(c);
Use longer and better names. s --&gt; song, a --&gt; album, c --&gt; context, tmpList --&gt; songs.
tmpList = null; in the bottom of the method will have no effect whatsoever. You can safely remove that line.