2

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.

0

3 Answers 3

7
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);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

1 Comment

The functionality for comparing is implemented in the Integer-Class. So you should not implement your own solution (substraction). Use the compareTo method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.