Sorting an array is an easy task in java especially if its in natural order or should we say in ascending order. This java tutorial is very helpful in designing a real life java applications. Complete java array example source code is provided below which you can modify for your own personal use. How to sort an array in ascending order is very easy however in descending order, we need to use a more complicated API.

Instructions in sorting an array of objects in Java

Consider an array of string objects “one”, “two”, “three”. Sort it out using java API in ascending and descending order. Print on the console the initial contents of the array, ascending order, and descending order.

Java API that is used in this example

java.util.Arrays class is a member of the Java Collections Framework

  • sort(Objects[] obj) – this method sort the array of objects in natural order
  • sort(Objects[] obj,Comparator c) – specified array of objects were sorted out using the specified comparator

java.util.Collections is also a member of the Java Collections Framework which we needed for the sorting

  • reverseOrder() – this method of the Collections class returns a comparator that implements a reverse of the natural ordering of a collections of objects which in this case its an array of String.

Sort an Array Example Source code

package com.javatutorialhq.tutorial;

import java.util.Arrays;

import java.util.Collections;;
/**
* This java sample source code that shows
* how to sort an array of objects
* java array examples
* Property of javatutorialhq.com
* Feel free to modify for your own personal use
* All Rights Reserved
* Version 1.0
* 07/08/2013
*/

public class ArraySort {

	public static void main(String[] args) {

		// example of an array in java
		String[] arrayString = new String[] {"one","two","three"};

		System.out.println("Printing the initial contents");
		for(String s:arrayString){
			System.out.println(s);
		}
		//Sorting the array in natural order
		Arrays.sort(arrayString);
		System.out.println("Printing the sorted array in ascending order");
		for(String s:arrayString){
			System.out.println(s);
		}

		// example on how to sort an array in reverse or descending order
		Arrays.sort(arrayString, Collections.reverseOrder());
		System.out.println("Printing the sorted array in descending order");
		for(String s:arrayString){
			System.out.println(s);
		}

	}

}

Sample Console Output using eclipse for java

 Printing the initial contents
 one
 two
 three
 Printing the sorted array in ascending order
 one
 three
 two
 Printing the sorted array in descending order
 two
 three
 one