Reputation: 287
I have pairs of list and i want to sort by Pair.second if Pair.first is not null
my list
val list = listOf<Pair<Int?, Int>>(
Pair(1, 199),
Pair(null, 180),
Pair(10, 210),
Pair(null, 178)
)
Desired result
Pair(1, 199),
Pair(10, 210),
Pair(null, 178),
Pair(null, 180)
Upvotes: 1
Views: 2444
Reputation: 7163
You could split the list into two lists, one containing the pairs with the null value, the other containing the others, and then sort each group by the second value:
val list = listOf(
Pair(1, 199),
Pair(null, 180),
Pair(10, 210),
Pair(null, 178)
)
val result = list
.groupBy { it.first == null }
.flatMap { (_, subList) -> subList.sortedBy { it.second } }
result.forEach(::println)
Output:
(1, 199)
(10, 210)
(null, 178)
(null, 180)
Upvotes: 1
Reputation: 17248
I suggest checking out this question: How to sort based on/compare multiple values in Kotlin?
You can combine multiple sort criteria, first push null
s to the end then compare the fields:
val result = list.sortedWith(
compareBy<Pair<Int?, Int>> { it.first == null } // sort nulls explicitly or they'll end up before non-null values
.thenBy{ it.first }
.thenBy{ it.second }
)
Upvotes: 3
Reputation: 19524
You can just use an elvis operator to default to using the second item if the first is null
list.sortedBy { it.first ?: it.second }
Upvotes: 1