简体   繁体   English

我如何按字母顺序对这个数组列表排序?

[英]How would i alphabetically sort this arraylist?

So i have an ArrayList with a hashmap that returns a list of songs. 所以我有一个带有哈希表的ArrayList ,该哈希表返回歌曲列表。 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;
}

You will need to implement a Comparator and use Collections.sort 您将需要实现一个Comparator并使用Collections.sort

See this relevant answer: https://stackoverflow.com/a/18441978/288915 请参阅以下相关答案: https : //stackoverflow.com/a/18441978/288915

You can use Collections.sort with an anonymous comparator that compares song's titles, eg: 您可以将Collections.sort与用于比较歌曲标题的anonymous comparator一起使用,例如:

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;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按字母顺序然后按数字对ArrayList进行排序 - How to sort ArrayList alphabetically then by number 如何按字母顺序对 ArrayList&lt;&gt; 的元素进行排序? - How to sort the elements of an ArrayList<> alphabetically? Android:如何按字母顺序对特殊字符的数组列表进行排序? - Android : How To Sort An Arraylist of Special Characters Alphabetically? 如何插入按字母顺序对字符串的ArrayList排序 - How to insertion sort an ArrayList of Strings alphabetically 按字母顺序排序ArrayList - Sort ArrayList alphabetically 如何不使用collections.sort()按字母顺序对数组列表排序 - How to sort an arraylist alphabetically without using collections.sort(); 我将如何对在 Java 中格式化为高度的字符串数组列表进行排序? - How would I sort an arraylist of strings that's formatted as a height in java? 我如何按项目类型按字母顺序对我的Java链接(而非集合LinkedList)列表进行排序? - How would I sort my java linked(not collections LinkedList) list by item type alphabetically? 按字母顺序排列复杂对象的arraylist - sort arraylist of complex objects alphabetically 我如何根据另一个ArrayList的行为对ArrayList进行排序? (Java)的 - How would I sort an ArrayList based on how another ArrayList acts? (java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM