Home > database >  How to sort in kotlin with condition
How to sort in kotlin with condition

Time:03-27

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)

CodePudding user response:

I suggest checking out this question: How to sort based on/compare multiple values in Kotlin?

You can combine multiple sort criteria, first push nulls 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 }
)

CodePudding user response:

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 }

CodePudding user response:

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)
  • Related