KOTLIN Compare n dimensional array

Viewed 80

I need to sort list of list of list... I have something like this in python:

a = sorted([[[1,2],[3,4]],[[1]]])

Is there something like this in Kotlin? I found custom comparator objects which is really confusing for such a simple task.

1 Answers

If I understood Python sorted() method correctly, this should produce the same behavior:

fun main() {
    val a = listOf(listOf(listOf(1,2),listOf(4,3)), listOf(listOf(0,2,1)),listOf(listOf(1)))
    val b =a.sortedBy {it -> it.size}
    println(a)
    println(b)
}

Output:

[[[1, 2], [4, 3]], [[0, 2, 1]], [[1]]]
[[[0, 2, 1]], [[1]], [[1, 2], [4, 3]]]

Python equivalent:

a = [[[1,2],[4,3]], [[0,2,1]] ,[[1]]]
b = sorted(a)
print(a)
print(b)

Output:

[[[1, 2], [4, 3]], [[0, 2, 1]], [[1]]]
[[[0, 2, 1]], [[1]], [[1, 2], [4, 3]]]
Related