【问题标题】:Sort Arraylist in alphabetical order按字母顺序对 Arraylist 进行排序
【发布时间】:2017-05-22 18:38:21
【问题描述】:

我正在从arrayList 制作listView。现在我希望listView 按字母顺序排序。我已经在网上搜索过,但没有一个有效。我怎样才能实现它?

我的代码:

String[] Hospitals = getResources().getStringArray(R.array.Hospitals);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Hospitals);

mListView.setAdapter(adapter);

“医院”是我的 strings.xml 文件中的一个列表。

【问题讨论】:

  • “我已经在网上搜索过,但没有一个成功”,您搜索并尝试了什么?
  • 为什么不只对 arrayList 进行排序?
  • 这是对 List developer.android.com/reference/java/util/… 进行排序的方法,只需从您的数组中创建一个 ArrayList 并使用它。

标签: android listview arraylist


【解决方案1】:

就像你说的,Hospitals 不是一个 Arraylist,而只是一个字符串数组 (String[]),所以你需要使用这个:

List<String> list = Arrays.asList(etst);

那么就可以使用下面的代码进行排序了

Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.compareTo(s2);
            }
        });

如果你想要它忽略大小写:

Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

【讨论】:

    【解决方案2】:

    使用 Arrays.sort(Hospitals) 对数组进行排序。

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 2019-08-02
      • 2013-10-28
      • 2013-09-09
      • 2011-01-30
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多