Java Arrays sort in Descending order

By | July 3, 2019

Task: How to use Java Arrays sort method for Descending order.

How To Use Arrays.sort() method to Sort Arrays in Descending Order?

In a previous post, we wrote a Java program to sort array in ascending order using Arrays.sort(array-name) method. We can use the following syntax to sort in descending order: Arrays.sort(array, Collections.reverseOrder());

Here we need to use: import java.util.Collections; too along with using import java.util.Arrays;

Java Arrays sort in Descending order

Java Arrays sort in Descending order

Moreover, Collections.reverseOrder() does not support primitive data types like int, float, double, char etc. Therefore, we will change code for using Integer array instead of using int array.

Integer a[]={ 201, 145, 109, 89, 21, 17, 10, 6, 0, -1 };

The Source code of the Java program to sort Integer array in descending order is:

/*
 * Write a Java program to input integer 
array and use Arrays.sort() method to
sort in descending order
 */
package arrayssort;
import java.util.Arrays;
import java.util.Collections;
/**
  * @author www.EasyCodebook.com
 */
public class ArraysSort {

    public static void main(String[] args) {
       // We will use Integer[] instead of int[] array
       // because Collections.reverseOrder doesn't 
        // work for primitive data types like int.
        //So we use Wrapper class Integer instead of int[] array
        Integer[] a = {10, 17, 6, 145, 201, 109, 21, 89, 0, -1}; 
  
        Arrays.sort(a, Collections.reverseOrder()); 
        System.out.printf("Array in Descending order is : %s", 
                                     Arrays.toString(a)); 
    }
    
}

The output of the Java program to sort Integer array in descending order is:

Array in Descending order is : [201, 145, 109, 89, 21, 17, 10, 6, 0, -1]

Loading

One thought on “Java Arrays sort in Descending order

  1. Pingback: Java Arrays sort Method to Sort Arrays | EasyCodeBook.com

Leave a Reply

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