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.


Sort a String Array

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


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

Main method to sort an Array


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


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 *