【发布时间】:2011-08-14 11:26:54
【问题描述】:
我有一个字符串数组列表'names'。其中包含人名。我想按字母顺序对数组列表进行排序。请帮助我
【问题讨论】:
我有一个字符串数组列表'names'。其中包含人名。我想按字母顺序对数组列表进行排序。请帮助我
【问题讨论】:
这会解决你的问题...
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 对象进行排序,请使用 Collection.sort 方法。这是一个
静态方法。它将 ArrayList 对象的元素按升序排序。
以防万一下面的注释中的代码不起作用意味着...
试试这个代码..
创建自定义比较器类:
import java.util.Comparator;
class IgnoreCaseComparator implements Comparator<String> {
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
然后按你的排序:
IgnoreCaseComparator icc = new IgnoreCaseComparator();
java.util.Collections.sort(arrayList,icc);
【讨论】:
Collections.sort(path, String.CASE_INSENSITIVE_ORDER);,这将忽略大小写并比较你的字符串......
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
/*
* Create a collections of colours
*/
List colours = new ArrayList();
colours.add("red");
colours.add("green");
colours.add("blue");
colours.add("yellow");
colours.add("cyan");
colours.add("white");
colours.add("black");
/*
* We can sort items of a list using the Collections.sort() method.
* We can also reverse the order of the sorting by passing the
* Collections.reverseOrder() comparator.
*/
Collections.sort(colours);
System.out.println(Arrays.toString(colours.toArray()));
Collections.sort(colours, Collections.reverseOrder());
System.out.println(Arrays.toString(colours.toArray()));
}
【讨论】:
嗨 seethalakshmi 用于在 Arraylist 上进行排序,您需要比较器和集合
只要通过这个链接http://ventrix.nsdc.gr/code_folds/?p=119,你就可以轻松实现它
【讨论】: