coinhndp
coinhndp

Reputation: 2481

Sort list of list Kotlin

I have a list of (x, y) in which y can only be 0 or 1 like this

For example :

[(3, 0), (3, 1), (5, 1)]
[(5, 0), (3, 1), (5, 1)]
[(1, 1), (3, 1), (5, 1)]
[(3, 0), (4, 0), (5, 1)]
[(5, 0), (4, 0), (5, 1)]
[(1, 1), (4, 0), (5, 1)]
[(3, 0), (3, 1), (5, 1)]
[(5, 0), (3, 1), (5, 1)]
[(1, 1), (3, 1), (5, 1)]

How can I sort the list so that the sublist with the most y = 0 will be on the top?

Upvotes: 5

Views: 5579

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 82117

Simply use sortedBy which sorts in ascending order (i.e. 0 before 1 etc.) in combination with sumBy, summing the values of y in the sublists:

list.sortedBy { it.sumBy { it.y } }

KDoc:

Returns a list of all elements sorted according to natural sort order of the value returned by specified selector function.

You'll get a list, in which the sublists are ordered in ascending order regarding their number of elements with y = 0.

Note that summing up all y values as in sumBy only works since 0 and 1 are the only possible values in the given scenario.

Upvotes: 4

Januson
Januson

Reputation: 4861

Asuming coordinates representation below:

class Point(val x: Int, val y: Int)

You can simply use sortedByDescending on your list of lists and as a sorting condition count occurences of y = 0 in sublists. With descending order the sublist with most y = 0 will be the first.

val sorted = input.sortedByDescending { it.count { it.y == 0 } }

Upvotes: 4

Related Questions