Sort an array using Arrays.sort() in Java in ascending or descending order

Arrays.sort() can be used to sort arrays in Java in ascending / descending order.

Arrays.sort( array ); – This method is used to sort an array in ascending order.
Arrays.sort( array, Collections.reverseOrder() ); – To sort an array in descending order.

Primitives cannot be sorted in reverse using this method. So if you want to sort int, convert it into an Integer first and then sort.

Example 1: Sort a numeric array

import java.util.Arrays;
import java.util.Collections;

class CollectionTest
{
    public static void main ( String[] args )
    {
        int[] array = { 7, 3, 1, 2, 5 } ;
        Arrays.sort( array );
        System.out.println( Arrays.toString( array ) );

        Integer[] array2 = Arrays.stream( array ).boxed().toArray( Integer[]::new );
        Arrays.sort( array2, Collections.reverseOrder() );
        System.out.println( Arrays.toString( array2 ) );
    }
}

Output:

[1, 2, 3, 5, 7]
[7, 5, 3, 2, 1]

Example 2: Sort an alphanumeric array

import java.util.Arrays;
import java.util.Collections;

class CollectionTest
{
    public static void main ( String[] args )
    {
        String[] array = { “Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn” } ;
        Arrays.sort( array );
        System.out.println( Arrays.toString( array ) );

        Arrays.sort( array, Collections.reverseOrder() );
        System.out.println( Arrays.toString( array ) );
    }
}

Output:

[Earth, Jupiter, Mars, Mercury, Saturn, Venus]
[Venus, Saturn, Mercury, Mars, Jupiter, Earth]

Leave a Comment

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