How to sort an Array in java

Java example to show the use of Arrays.sort() to sort an Array. The code should be self-explanatory.


import java.util.Arrays;
import java.util.Collections;

public class ArraySorting{
	
	public static void main(String args[]){
		
		String[] unsortStringArray = new String[] {"c", "b", "a", "3", "2", "1"}; 
		int[] unsortIntArray = new int[] {7,5,4,6,1,2,3}; 
		
		System.out.println("Before sort");
		System.out.println("--- unsortStringArray ---");
		for(String temp: unsortStringArray){
			System.out.println(temp);
		}
		System.out.println("--- unsortIntArray ---");
		for(int temp: unsortIntArray){
			System.out.println(temp);
		}
		
		//sort it
		Arrays.sort(unsortStringArray);
		Arrays.sort(unsortIntArray);
		
		System.out.println("After sorted");
		System.out.println("--- unsortStringArray ---");
		for(String temp: unsortStringArray){
			System.out.println(temp);
		}
		System.out.println("--- unsortIntArray ---");
		for(int temp: unsortIntArray){
			System.out.println(temp);
		}
		
		//sort it, reverse order
		Arrays.sort(unsortStringArray,Collections.reverseOrder());
		
		System.out.println("After sorted - reserved order");
		System.out.println("--- unsortStringArray ---");
		for(String temp: unsortStringArray){
			System.out.println(temp);
		}

	}
	
}

Output


Before sort
--- unsortStringArray ---
c
b
a
3
2
1
--- unsortIntArray ---
7
5
4
6
1
2
3
After sorted
--- unsortStringArray ---
1
2
3
a
b
c
--- unsortIntArray ---
1
2
3
4
5
6
7
After sorted - reserved order
--- unsortStringArray ---
c
b
a
3
2
1

Reference

  1. Arrays documentation

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
anurag Recent comment authors
newest oldest most voted
anurag
Guest
anurag

this example is very nice and well explained
thanks