Java Array Sort descending?

2019-01-01 10:45发布

问题:

Is there any EASY way to sort an array in descending order like how they have a sort in ascending order in the Arrays class?

Or do I have to stop being lazy and do this myself :[

回答1:

You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collection.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with Integer array but will not work with an int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.



回答2:

You can use this:

    Arrays.sort(data, Collections.reverseOrder());

Collections.reverseOrder() returns a Comparator using the inverse natural order. You can get an inverted version of your own comparator using Collections.reverseOrder(myComparator).



回答3:

for a list

Collections.sort(list, Collections.reverseOrder());

for an array

Arrays.sort(array, Collections.reverseOrder());


回答4:

without explicit comparator:

Collections.sort(list, Collections.reverseOrder());

with explicit comparator:

Collections.sort(list, Collections.reverseOrder(new Comparator()));


回答5:

an alternative could be (for numbers!!!)

  1. multiply the Array by -1
  2. sort
  3. multiply once again with -1

Literally spoken:

array = -Arrays.sort(-array)


回答6:

Java 8:

Arrays.sort(list, comparator.reversed());

Update: reversed() reverses the specified comparator. Usually, comparators order ascending, so this changes the order to descending.



回答7:

For array which contains elements of primitives if there is org.apache.commons.lang(3) at disposal easy way to reverse array (after sorting it) is to use:

ArrayUtils.reverse(array);


回答8:

I don\'t know what your use case was, however in addition to other answers here another (lazy) option is to still sort in ascending order as you indicate but then iterate in reverse order instead.



回答9:

First you need to sort your array using:

        Collections.sort(Myarray);

Then you need to reverse the order from ascending to descending using:

        Collections.reverse(Myarray);


回答10:

Another solution is that if you\'re making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).

For Example :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= 1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= -1;
    return ret;
}

Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it\'s magnitude. So in order to correct that, you switch the values returned by the < and >. This gives you the following :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= -1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= 1;
    return ret;
}

To make use of this compareTo, we simply call Arrays.sort(mFreq) which will give you the sorted array freq [] mFreq.

The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I\'d encourage you not to think that way, it actually isn\'t. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.



回答11:

array.sort(function(a, b) {return b - a;}); //descending 

or

array.sort(function(a, b) {return a - b;}); //ascending


回答12:

I know that this is a quite old thread, but here is an updated version for Integers and Java 8:

Arrays.sort(array, (o1, o2) -> o2 - o1);

Note that it is \"o1 - o2\" for the normal ascending order (or Comparator.comparingInt()).

This also works for any other kinds of Objects. Say:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());


回答13:

This worked for me:

package doublearraysort;

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

public class Gpa {


    public static void main(String[] args) {
        // initializing unsorted double array
        Double[] dArr = new Double[] {                 
            new Double(3.2),
            new Double(1.2),
            new Double(4.7),
            new Double(3.3),
            new Double(4.6),
           };
        // print all the elements available in list
        for (double number : dArr) {
            System.out.println(\"GPA = \" + number);
        }

        // sorting the array
        Arrays.sort(dArr, Collections.reverseOrder());

        // print all the elements available in list again
        System.out.println(\"The sorted GPA Scores are:\");
        for (double number : dArr) {
            System.out.println(\"GPA = \" + number);
        }
    }
}

Output:

GPA = 3.2
GPA = 1.2
GPA = 4.7
GPA = 3.3
GPA = 4.6
The sorted GPA Scores are:
GPA = 4.7
GPA = 4.6
GPA = 3.3
GPA = 3.2
GPA = 1.2


回答14:

public double[] sortArrayAlgorithm(double[] array) { //sort in descending order
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            if (array[i] >= array[j]) {
                double x = array[i];
                array[i] = array[j];
                array[j] = x;
            }
        }
    }
    return array;
}

just use this method to sort an array of type double in descending order, you can use it to sort arrays of any other types(like int, float, and etc) just by changing the \"return type\", the \"argument type\" and the variable \"x\" type to the corresponding type. you can also change \">=\" to \"<=\" in the if condition to make the order ascending.