在Android的排序字符串数组列表数组、字符串、列表、Android

2023-09-05 05:58:58 作者:且笑天下江山如画

我有一个字符串数组列表names'.which包含people.i的名字要排序的字母ArrayList中order.plz帮我

i am having a string arraylist 'names'.which contains names of people.i want to sort the arraylist in alphabetical order.plz help me

推荐答案

这将解决您的问题...

This will solve your problem...

ArrayList arrayList = new ArrayList();

//Add elements to Arraylist
arrayList.add("1");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");


Collections.sort(arrayList);

//display elements of ArrayList
System.out.println("ArrayList elements after sorting in ascending order : ");
for(int i=0; i<arrayList.size(); i++)
    System.out.println(arrayList.get(i));

要排序的ArrayList对象,使用 Col​​lection.sort 方法。这是一个 静态方法。它的排序ArrayList对象的元素融入升序排列。

To sort an ArrayList object, use Collection.sort method. This is a static method. It sorts an ArrayList object's elements into ascending order.

以防万一,若跌破code的评论不工作是指... 试试这个code ..

Just in case if the below code in comment doesnt work means... Try this code..

创建一个自定义比较器类:的

import java.util.Comparator;

class IgnoreCaseComparator implements Comparator<String> {
  public int compare(String strA, String strB) {
    return strA.compareToIgnoreCase(strB);
  }
}

然后在你的排序:

Then on your sort:

IgnoreCaseComparator icc = new IgnoreCaseComparator();

java.util.Collections.sort(arrayList,icc);