【问题标题】:How would i alphabetically sort this arraylist?我将如何按字母顺序对这个数组列表进行排序?
【发布时间】:2016-07-15 20:43:48
【问题描述】:

所以我有一个ArrayList,带有一个返回歌曲列表的哈希图。所以我的问题是,我将如何修改此代码以使其按字母顺序返回歌曲?

这是代码...

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

【问题讨论】:

  • 为什么要在 Array 中使用 HashMap?使用 Map.Entry 数组,例如 array = new ArrayList>();那么你可以使用 Collections.sort 并像用户“kevingreen”所说的那样实现一个比较器。
  • 别忘了定义你的songsList ArrayList 变量!

标签: java android arraylist


【解决方案1】:

您需要实现Comparator 并使用Collections.sort

查看此相关答案:https://stackoverflow.com/a/18441978/288915

【讨论】:

    【解决方案2】:

    您可以使用Collections.sortanonymous 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;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      相关资源
      最近更新 更多