Java Comparator Class to Sort Arrays

Java Comparator Class to Sort Arrays

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];
}

5 Answers

[...] 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]);
    }
});
5

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.

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.

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]

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]));
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.