Kotlin sorting nulls last

You can use these functions from the kotlin.comparisons package:

  • fun <T: Comparable<T>> nullsLast(): Comparator<T?>, which constructs a comparator of something comparable that just puts nulls after all not-null values;

  • fun <T, K> compareBy(comparator: Comparator<in K>, selector: (T) -> K): Comparator<T>, which accepts a comparator and a function that provides values for the comparator, combining them into a new comparator;

This will let you make a comparator that compares SomeObject by nullableField putting nulls last. Then you can simply pass the comparator to
fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T>, which sorts an iterable into a list using a comparator:

val l = listOf(SomeObject(null), SomeObject("a"))

l.sortedWith(compareBy(nullsLast<String>()) { it.nullableField }))
// [SomeObject(nullableField=a), SomeObject(nullableField=null)]

Leave a Comment