Jamie Smith
Jamie Smith

Reputation: 131

How would i alphabetically sort this arraylist?

So i have an ArrayList with a hashmap that returns a list of songs. So my question is, how would i modify this code so that it returns the songs in alphabetical order?

Heres the code...

public ArrayList<HashMap<String, String>> getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }

    // return songs list array
    return songsList;
}

Upvotes: 2

Views: 132

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can use Collections.sort with an anonymous comparator that compares song's titles, e.g.:

Collections.sort(list, new Comparator<Map<String, String>>() {
    public int compare(Map<String, String> o1, Map<String, String> o2) {
        if (o1.containsKey("songTitle") && o2.containsKey("songTitle")) {
            return o1.get("songTitle").compareTo(o2.get("songTitle"));
        }
        return 0;
    }
});

Upvotes: 2

kevingreen
kevingreen

Reputation: 1541

You will need to implement a Comparator and use Collections.sort

See this relevant answer: https://stackoverflow.com/a/18441978/288915

Upvotes: 2

Related Questions