我有一个字符串arraylist'names'.which包含people.i的名字想按字母顺序排序arraylist.plz帮助我
Hus*_*ain 57
这将解决您的问题......
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));
Run Code Online (Sandbox Code Playgroud)
要对ArrayList对象进行排序,请使用Collection.sortmethod.这是一种静态方法.它将ArrayList对象的元素按升序排序.
以防万一注释中的以下代码无效...请尝试此代码..
创建自定义比较器类:
import java.util.Comparator;
class IgnoreCaseComparator implements Comparator<String> {
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的排序:
IgnoreCaseComparator icc = new IgnoreCaseComparator();
java.util.Collections.sort(arrayList,icc);
Run Code Online (Sandbox Code Playgroud)
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()));
}
Run Code Online (Sandbox Code Playgroud)