2

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;
}
Jamie Smith
  • 131
  • 8
  • Why do you use a HashMap inside an Array? Use an Array of Map.Entry, like array = new ArrayList>(); then you could use Collections.sort and implement a Comparator like user "kevingreen" said. – GuilhE Mar 28 '16 at 15:01
  • Don't forget to define your songsList ArrayList variable! – Brian Risk Mar 28 '16 at 15:09

2 Answers2

2

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

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

Community
  • 1
  • 1
kevingreen
  • 1,541
  • 2
  • 18
  • 40
2

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;
    }
});
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102