wellnwill Marathahalli Bangalore

Sorting in java

There are two conditions to sort an object based on default sorting order:

  • Data should be homogeneous.
  • An object should be comparable.

An object is said to be comparable if corresponding class implements comparable interface.

Note:String and Wrapper classes implement comparable interface.

To sort an array elements

Arrays class present in java.util package. This class provides some utility methods to perform operations with array object.

Arrays.sort(array object):

  • This method sorts the specified array into default sorting order i.e. ascending order.
  • This method is a static method of Arrays class present in util package.
import java.util.Arrays;
class Test255
{
public static void main(String args[]){
char ch[] ={'D','A','C','B'};
Arrays.sort(ch);
for(int i=0;i < ch.length;i++) 
System.out.println(ch[i]);  
}
}
//O/P-A,B,C,D



import java.util.Arrays;
class Test256{
public static void main(String args[]){
String name[]= new String[] {"Trump","Obama","Modi"};
for(int i=0; i < name.length;i++) 
System.out.println(name[i]);  
System.out.println("after sorting:");
Arrays.sort(name);
for(String temp: name){
System.out.println(temp);
}
}
}
//O/P-Modi,Obama,Trump
import java.util.Arrays;
class Test257
{
public static void main(String args[])
{
int id[]= new int[] {1,4,3,6,5,2};
for(int i=0;i < id.length;i++) 
System.out.println(id[i]);  
System.out.println("after sorting:");
Arrays.sort(id);
for(int temp: id)
{
System.out.println(temp);
}
}
}
//O/P-1,2,3,4,5,6

To sort List elements

Collections.sort(List object):

  • This method sorts the elements of list(i.e. ArrayList and LinkedList).
  • This method is a static method of Collections class present in util package.
  • Object should be comparable type and object will be sorted based on natural order defined by compareTo() method.
import java.util.*;
class Test258{
public static void main(String args[]){
List  name= new ArrayList();
name.add("Trump");
name.add("Obama");
name.add("Modi");  
System.out.println("after sorting:");
Collections.sort(name);
for(Object temp: name)
{
System.out.println(temp);
}
}
}
//O/P- Modi,Obama,Trump
import java.util.*;  
class ListSort1{  
public static void main(String args[]){  
ArrayList al=new ArrayList();  
al.add("Viru");  
al.add("Saurav");  
al.add("Mukesh");  
al.add("Tahir");  
Arrays.sort(al);  
Iterator itr=al.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
 }  
}  
}
 //O/P-CTE. 
Footer with Map