Java Collections Framework:ArrayList-3(ArrayList Sorting)

 

How to sort ArrayList in Java

Example 1: Sorting of ArrayList<String>

Here we are sorting the ArrayList of String type. We are doing it by simply calling the Collections.sort(arraylist) method. The output List will be sorted alphabetically.

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

Output:



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

Example 2: Sorting of ArrayList<Integer>

The same Collections.sort() method can be used for sorting the Integer ArrayList as well.

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

Output:

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


Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Selenium-Java Contents

Java OOPS:Constructors in Java – A complete study!!