Java Sorting

Today we are going to take care of java sorting. We are going to show you how to sort Arrays and Collections in Java.

Sorting Arrays

Here is a code snippet where we sort an Array of Integer objects.

ArraySorting.java

package com.itcuties.java.sorting;

import java.util.Arrays;

/**
 * Sorting Java Arrays.
 * 
 * @author itcuties
 *
 */
public class ArraySorting {
	public static void main(String[] args) {
		
		/////////////////////////////// Sorting Numeric types
		int[] integerArray = new int[] {7,3,2,45,6,2,3,4,5,5,3,2,1,7,8,4,3,3,2};
		
		// Sort
		Arrays.sort(integerArray);
		
		// Display sorted
		for (int i: integerArray)
			System.out.print(i + " ");
		
	}
}

Calling Arrays.sort(ARRAY) sorts the array to which the reference is being passed in the parameter. When you will run this code you’ll get:

1 2 2 2 2 3 3 3 3 3 4 4 5 5 6 7 7 8 45

Sorting Collections

Here is an example of sorting an ArrayList object containing String elements.

CollectionSorting.java

package com.itcuties.java.sorting;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Sorting Java Collections
 * 
 * @author itcuties
 *
 */
public class CollectionSorting {
	public static void main(String[] args) {
		
		/////////////////////////////// Sorting Strings
		ArrayList<String> stringList = new ArrayList<String>();
		stringList.add("Mercedes");
		stringList.add("Audi");
		stringList.add("BMW");
		stringList.add("Honda");
		stringList.add("Toyota");

		// Sort
		Collections.sort(stringList);

		// Display sorted
		for (String s: stringList)
			System.out.print(s + " ");		

	}
}

In this case calling Collections.sort(COLLECTION) does the trick. Running this code results in the following output:

Audi BMW Honda Mercedes Toyota

Don’t do it at home!

Here is an example where an Array of objects of type Object is being sorted.

/////////////////////////////// Sorting Objects
Object[] objectsArray = new Object[] {"Mercedes", 7, "Audi", "BMW", 4, 8.7, 1, "Honda", "Toyota"};

// Sort
Arrays.sort(objectsArray);	// This doesn't work. java.lang.ClassCastException is being thrown.

This code compiles but results in java.lang.ClassCastException being thrown.

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at java.lang.String.compareTo(Unknown Source)
	at java.util.Arrays.mergeSort(Unknown Source)
	at java.util.Arrays.mergeSort(Unknown Source)
	at java.util.Arrays.sort(Unknown Source)

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW