53

Say, we have the following 2-dimensional array:

int camels[][] = new int[n][2];

How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order using Arrays.sort(camels, comparator)? The compare function for reference is:

@Override public int compare(int[] a, int [] b)
{
    return b[0] - a[0];
}
aioobe
  • 413,195
  • 112
  • 811
  • 826
Leonid
  • 22,360
  • 25
  • 67
  • 91

5 Answers5

107

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Sorry to bring up an old thread but why was there a need to cast to Integer when you return the compare method? – Evolutionary High Aug 21 '13 at 02:52
  • 1
    @EvolutionaryHigh, because you can't call `.compareTo` on an `int`. – aioobe Aug 21 '13 at 09:45
  • Also the @Override annotation won't work in java 5. http://stackoverflow.com/questions/987973/why-does-eclipse-complain-about-override-on-interface-methods – jontro Oct 08 '14 at 16:25
  • Oh gosh. Such small use case that have evolved in from 4, to 5, to 6, to 7, to 8 :-) Kind of interesting. – aioobe Oct 08 '14 at 16:28
  • I think closure in Swift may refer to this to make its own format, e.g. `sort() {$1 > $2}`, all about anonymous function. – Zhou Haibo Apr 02 '21 at 05:03
  • What should I add in the above code if I want to sort this 2d array in increasing order of the first element and if the first elements of two 1 d arrays are same the sort them according to the second element? – sam2611 Dec 16 '22 at 15:26
9

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

user2830451
  • 2,126
  • 5
  • 25
  • 31
9

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

Tarun Kolla
  • 917
  • 1
  • 10
  • 30
user3706706
  • 93
  • 1
  • 4
0

java.nio.IntBuffer#wrap(int[]) provides an excellent built-in way to compare two instances of int[], since IntBuffer is both a lightweight wrapper for int[] instances, and implements Comparable. Using it combined with other built-in Comparator features has several advantages over the examples in other answers I see here:

  • Compares all sub-array elements
  • Supports variable sub-array lengths
  • Supports null array elements

This example sorts the arrays in descending order, putting null array elements last:

int[][] twoDim = {{1, 2}, {3, 7}, {8, 9}, {4, 2}, null, {5, 3}, {4}};
System.out.println("Unsorted: " + Arrays.deepToString(twoDim));

Comparator<int[]> c = Comparator.nullsFirst(Comparator.comparing(IntBuffer::wrap));
Arrays.sort(twoDim, c.reversed());
System.out.println("Sorted: " + Arrays.deepToString(twoDim));

Output:

Unsorted: [[1, 2], [3, 7], [8, 9], [4, 2], null, [5, 3], [4]]
Sorted: [[8, 9], [5, 3], [4, 2], [4], [3, 7], [1, 2], null]
Glenn Lane
  • 3,892
  • 17
  • 31
-1

Here's sorting Arraylist of Date Arrays. Maybe smb smwhen will need it.

List <Date[]> sortedDateList = new ArrayList<>(/* initialization */);
Collections.sort(sortedDateList, new Comparator<Date[]>() {
    @Override
    public int compare(Date[] d1, Date[] d2) {
        return (d1[0].compareTo(d2[0]));
    }
});
ahuemmer
  • 1,653
  • 9
  • 22
  • 29