By default, the ArrayList’s elements are display according to the sequence it is put inside. Often times, you may need to sort the ArrayList to make it alphabetically order. In this example, it shows the use of Collections.sort(‘List’) to sort an ArrayList.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class SortArrayList{
 
	public static void main(String args[]){
 
		List<String> unsortList = new ArrayList<String>();
 
		unsortList.add("CCC");
		unsortList.add("111");
		unsortList.add("AAA");
		unsortList.add("BBB");
		unsortList.add("ccc");
		unsortList.add("bbb");
		unsortList.add("aaa");
		unsortList.add("333");
		unsortList.add("222");
 
		//before sort
		System.out.println("ArrayList is unsort");
		for(String temp: unsortList){
			System.out.println(temp);
		}
 
		//sort the list
		Collections.sort(unsortList);
 
		//after sorted
		System.out.println("ArrayList is sorted");
		for(String temp: unsortList){
			System.out.println(temp);
		}
	}
 
}

Output

ArrayList is unsort
CCC
111
AAA
BBB
ccc
bbb
aaa
333
222
ArrayList is sorted
111
222
333
AAA
BBB
CCC
aaa
bbb
ccc

Reference

  1. ASCII table list
  2. Collections.sort() documentation
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts