Sort an Array in Java Example

Sort an Array in Java Example

In java programming language, we very widely use array. There are scenarios, where we need elements in sorted manner. Let us see how we can sort elements in array with examples.

Sort an Integer array

To sort an Integer array, use Arrays.sort() method.

package com.code2succeed.sorting.array;

import java.util.Arrays;

public class ArraySortExample {
	public static void main(String[] args) {
		int [] a = {12, 32, 43, 10, 5, 23, 99, 1};
		
		System.out.println("Array before sorting : "+Arrays.toString(a));
		Arrays.sort(a);
		
		System.out.println("Array after sorting : "+Arrays.toString(a));
	}
}

Output

Array before sorting : [12, 32, 43, 10, 5, 23, 99, 1]
Array after sorting : [1, 5, 10, 12, 23, 32, 43, 99]

Sort a String Array

We can use Arrays.sort() method just like above example to sort a String Array.

package com.code2succeed.sorting.array;

import java.util.Arrays;

public class ArraySortExample {
	public static void main(String[] args) {		
		String [] str = {"abc", "xyz", "aaa", "bca", "pqr", "stu", "xxx"};
		System.out.println("Array before sorting : "+Arrays.toString(str));
		Arrays.sort(str);
		
		System.out.println("Array after sorting : "+Arrays.toString(str));
	}
}

Output

Array before sorting : [abc, xyz, aaa, bca, pqr, stu, xxx]
Array after sorting : [aaa, abc, bca, pqr, stu, xxx, xyz]

Sort an Array which contains custom objects as element using comparable

In this example we have created one custom class Emp with firstName, lastName and age as instance variable. Emp class implements Comparable interface and sort Emp objects based on age.

Emp bean class
package com.code2succeed.sorting.comparable;

@SuppressWarnings("rawtypes")
public class Emp implements Comparable<Emp> {
	private String firstName;
	private String lastName;
	private int age;
	
	public Emp(){}
	public Emp(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("\nFirstName :"+firstName);
		sb.append(", LastName : "+lastName);
		sb.append(", age : "+age);
		
		return sb.toString();
	}
	@Override
	public int compareTo(Emp emp) {
		return this.age - emp.age;
	}
}
Main method to sort an Array
package com.code2succeed.sorting.array;

import java.util.Arrays;

import com.code2succeed.sorting.comparable.Emp;

public class ArrayComparableExample {
	public static void main(String[] args) {
		Emp [] emps = new Emp[5];
		emps[0] = new Emp("Charles", "Anderson", 34);
		emps[1] = new Emp("Rob", "Anderson", 31);
		emps[2] = new Emp("Sheen", "Chan", 45);
		emps[3] = new Emp("Rahul", "Mahadewan", 36);
		emps[4] = new Emp("Mona", "J", 25);
		
		System.out.println("Array before sorting : "+Arrays.toString(emps));
		Arrays.sort(emps);
		
		System.out.println("Array after sorting : "+Arrays.toString(emps));
	}
}

Output

Array before sorting : [
FirstName :Charles, LastName : Anderson, age : 34, 
FirstName :Rob, LastName : Anderson, age : 31, 
FirstName :Sheen, LastName : Chan, age : 45, 
FirstName :Rahul, LastName : Mahadewan, age : 36, 
FirstName :Mona, LastName : J, age : 25]

Array after sorting : [
FirstName :Mona, LastName : J, age : 25, 
FirstName :Rob, LastName : Anderson, age : 31, 
FirstName :Charles, LastName : Anderson, age : 34, 
FirstName :Rahul, LastName : Mahadewan, age : 36, 
FirstName :Sheen, LastName : Chan, age : 45]

We have sorted the Array which contains custom object as elements using Comparable. In Emp class, we have used “age” as a parameter to sort the elements of the array. But, what if we want to sort the array using other parameters for example, based on “firstName”. So, by using Comparable we can only sort elements on one parameter. To sort objects on different parameter we should use Comparator interface. Here is example to sort an array using Comparator interface using “firstName” as sort criteria.

Sort an Array which contains custom objects as element using Comparator

package com.code2succeed.sorting.array;

import java.util.Arrays;
import java.util.Comparator;

import com.code2succeed.sorting.comparable.Emp;

public class ArrayComparatorExample {
	public static void main(String[] args) {
		Emp [] emps = new Emp[5];
		emps[0] = new Emp("Charles", "Anderson", 34);
		emps[1] = new Emp("Rob", "Anderson", 31);
		emps[2] = new Emp("Sheen", "Chan", 45);
		emps[3] = new Emp("Rahul", "Mahadewan", 36);
		emps[4] = new Emp("Mona", "J", 25);
		
		System.out.println("Array before sorting : "+Arrays.toString(emps));
		Arrays.sort(emps, new EmpComparator());
		
		System.out.println("Array after sorting : "+Arrays.toString(emps));
	}
}

class EmpComparator implements Comparator<Emp> {
	@Override
	public int compare(Emp emp1, Emp emp2) {
		return emp1.getFirstName().compareToIgnoreCase(emp2.getFirstName());
	}
}

Output

Array before sorting : [
FirstName :Charles, LastName : Anderson, age : 34, 
FirstName :Rob, LastName : Anderson, age : 31, 
FirstName :Sheen, LastName : Chan, age : 45, 
FirstName :Rahul, LastName : Mahadewan, age : 36, 
FirstName :Mona, LastName : J, age : 25]

Array after sorting : [
FirstName :Charles, LastName : Anderson, age : 34, 
FirstName :Mona, LastName : J, age : 25, 
FirstName :Rahul, LastName : Mahadewan, age : 36, 
FirstName :Rob, LastName : Anderson, age : 31, 
FirstName :Sheen, LastName : Chan, age : 45]

To Sort a List/ArrayList in java click here.
To Sort a Map/HashMap in java click here.

 

Leave a Reply

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