Sorting an Array in Descending (Reverse) Order


The Arrays class can be used to sort an array of either reference types or primitive types, but the Arrays class does have an overloaded sort method that can sort an array in any way we choose. That overloaded variant of the sort method can only take reference types, and it has an additional parameter which is of type Comparator. This is the parameter that tells how we want the array sorted. In the example below we call the static method reverseOrder on the Collections class. It returns a Comparator instance which will sort the array descending instead of normal ascending.
Since this overloaded sort method only take reference types, we have to use the proper wrapper class (in this case Integer) if we want to work with primitive types.


package com.javadb.examples;

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

/**
 *
 * @author www.javadb.com
 */

public class Main {

    /**
     * Example method for sorting an Integer array
     * in reverse order.
     */

    public void sortIntArrayReverseOrder() {
        
        Integer[] arrayToSort = new Integer[] {
            new Integer(48),
            new Integer(5),
            new Integer(89),
            new Integer(80),
            new Integer(81),
            new Integer(23),
            new Integer(45),
            new Integer(16),
            new Integer(2)
        };
        
        Arrays.sort(arrayToSort, Collections.reverseOrder());
        
        for (Integer i : arrayToSort) {
            System.out.println(i.intValue());
        }
            
    }

    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        Main main = new Main();
        main.sortIntArrayReverseOrder();
    }}



The output:


89
81
80
48
45
23
16
5
2

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: