# 如何在 Java 中对`ArrayList`进行排序

> 原文： [https://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/](https://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/)

在本教程中，我们分享了对[`ArrayList<String>`](https://beginnersbook.com/2013/12/java-arraylist/)和`ArrayList<Integer>`进行排序的示例。

**另请阅读：**

1.  [按降序排序`ArrayList`](https://beginnersbook.com/2013/12/sort-arraylist-in-descending-order-in-java/)
2.  [使用`Comparable`和`Comparator`排序`ArrayList`的对象](https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/)

## 示例 1：`ArrayList<String>`的排序

这里我们正在对`String`类型的`ArrayList`进行排序。我们只需调用`Collections.sort(arraylist)`方法即可。输出列表将按字母顺序排序。

```java
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);
		}
	}
}
```

输出：

```java
Before Sorting:
India
US
China
Denmark
After Sorting:
China
Denmark
India
US
```

## 示例 2：`ArrayList<Integer>`的排序

相同的[`Collections.sort()`](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List))方法也可用于对整数`ArrayList`进行排序。

```java
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);
		}
	}
}
```

输出：

```java
Before Sorting:
11
2
7
3
After Sorting:
2
3
7
11
```