I would like to sort a 2D array both row wise and column wise in Java. Is there a way to do that similar to following python code. I have array as numbers[][2];
python code
# it first sorts based on index 0; if they match, it reverse sort based on index 1
numbers.sort(key: lambda x:(x[0], -x[1]))
Can we achieve the same in Java through Arrays.sort(), if yes, what will be the comparator that I need to pass ?
You can use the following code:
Arrays.sort(
numbers,
Comparator.comparing((int[] x) -> x[0])
.thenComparing(
(int[] x) -> x[1],
Comparator.<Integer>naturalOrder().reversed()));
This uses the overload of Arrays.sort
that receives a Comparator
.
Maybe using a plain lambda expression is better:
Arrays.sort(
numbers,
(a, b) -> a[0] < b[0] ? -1 : a[0] > b[0] ? 1 :
a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.