Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 749
st.math Avatar asked Feb 13 '26 08:02

st.math


2 Answers

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);
  }
});
like image 127
schlagi123 Avatar answered Feb 15 '26 23:02

schlagi123


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

like image 30
Ganesh Jadhav Avatar answered Feb 15 '26 22:02

Ganesh Jadhav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!