在本教程中,我们分享了对ArrayList<String>
和ArrayList<Integer>
进行排序的示例。
示例 1:ArrayList<String>
的排序
这里我们正在对String
类型的ArrayList
进行排序。我们只需调用Collections.sort(arraylist)
方法即可。输出列表将按字母顺序排序。
import java.util.*;
public class Details {
public static void main(String args[]){
ArrayList<String> listofcountries = new ArrayList<String>();
listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");
/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
/* Sort statement*/
Collections.sort(listofcountries);
/* Sorted List*/
System.out.println("After Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
}
}
输出:
Before Sorting:
India
US
China
Denmark
After Sorting:
China
Denmark
India
US
示例 2:ArrayList<Integer>
的排序
相同的Collections.sort()
方法也可用于对整数ArrayList
进行排序。
import java.util.*;
public class ArrayListOfInteger {
public static void main(String args[]){
ArrayList<Integer> arraylist = new ArrayList<Integer>();
arraylist.add(11);
arraylist.add(2);
arraylist.add(7);
arraylist.add(3);
/* ArrayList before the sorting*/
System.out.println("Before Sorting:");
for(int counter: arraylist){
System.out.println(counter);
}
/* Sorting of arraylist using Collections.sort*/
Collections.sort(arraylist);
/* ArrayList after sorting*/
System.out.println("After Sorting:");
for(int counter: arraylist){
System.out.println(counter);
}
}
}
输出:
Before Sorting:
11
2
7
3
After Sorting:
2
3
7
11