Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]; } 
like image 493
Leonid Avatar asked Mar 22 '11 15:03

Leonid


People also ask

Can we sort array using Comparator?

The Comparator interface imposes the total ordering of on some collection of objects, through contract of the compare() method. The Arrays. sort(objectArray) method only works with a collection of objects that implement the Comparable interface, i.e. have natural ordering.

How do you sort elements using a Comparator?

Using Comparator we can sort ArrayList on the basis of multiple variables. We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface.

Which option is correct to sort the List using Comparator interface?

public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.

Which of the following methods is used to sort an array in Java system sort () array sort () arrays sort () collection sort?

Arrays class has a method called sort() which can be used to sort an array in-place.


1 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]);     } }); 
like image 73
aioobe Avatar answered Sep 24 '22 15:09

aioobe