How to sort an array using Comparator in Java ?

Published on July 8, 2015 by abundantcode

Filed under Java

Last modified July 8, 2015

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 1974 times

The Arrays.sort method in java lets the developers to sort an array of objects. The sort method also accepts the comparator object which can contain the sorting logic.

How to sort an array using Comparator in Java ?

Below is a sample code snippet demonstrating the usage of the Arrays.sort method with the comparator.

package com.abundantcode;
import java.util.Arrays;
import java.util.Comparator;

public class Main {

    public static void main(String[] args)

        String[] input = {"Java", "", "MCA Lab Programs", "B.E Java Lab Programs", "BCA Java Programs"};
        Arrays.sort(input,new Comparator<String>(){
            // This sorts in descending order
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);

        System.out.println("Sorted Array");
        for(String item:input)



If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment


You might be Interested in these Posts

How to use array Rank in C# ?

In C# , the Rank property of the array is is used to get the rank of the array. In simple terms , ra...

How to get the Number of Elements in an MultiDimensional Array in C# ?

In one of the previous articles , we demonstrated the usage of the Length property of the array in C...

How to get the Number of Elements in an Array in C# ?

You can use the Length property of the array to return the number of elements in it. Note that once ...