log_0
log_0

Reputation: 878

Java: Sorting a 2D array by first (int filled) column

I want to sort an Object[][] by the first column which consists of ints. Take, for example, this array:

Object[][] array = {{1, false, false}, {2, true, false}, {0, true, true}};

Now, I want to create a new array whose rows are sorted in a way that the first element of each row ascends:

Object[][] newArray = ...;
System.out.println(Arrays.deepToString(newArray));

What it should print: {{0, true, true}, {1, false, false}, {2, true, false}}

Thank you.

Upvotes: 2

Views: 3563

Answers (3)

Ganesh Jadhav
Ganesh Jadhav

Reputation: 802

Arrays in java has a sort method that takes in Comparator as 2nd parameter. You can pass in the parameter to be considered for sorting. In your case, we'll need to sort based on the first parameter of the input 2d array; the solution would look like:

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

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Upvotes: 2

You can use Array.sort method using a custom comparator as follows

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

Upvotes: 0

schlagi123
schlagi123

Reputation: 735

Arrays.sort(array, new Comparator<Object[]>() {
  @Override
  public int compare(Object[] o1, Object[] o2) {
    Integer i1 = (Integer) (o1[0]);
    Integer i2 = (Integer) (o2[0]);
    return i1.compareTo(i2);
  }
});

Upvotes: 7

Related Questions