Steve
10/31/2024, 10:20 PMJoffrey
10/31/2024, 10:25 PMval maybeSortedList = if (flag) list.sortedBy { it.prop } else list sortedDescendingBy { it.prop }
Steve
10/31/2024, 10:29 PMJoffrey
10/31/2024, 10:29 PMJoffrey
10/31/2024, 10:30 PMephemient
10/31/2024, 11:20 PMval ascList = list.sortedBy { it.prop }
val sortedList = if (asc) ascList else ascList.asReversed()
val comparator = compareBy(T::prop)
val sortedList = list.sortedWith(if (asc) comparator else comparator.reversed())
Norbert Kiesel
11/01/2024, 8:47 PMfun <T, R: Comparable<R>> List<T>.sortedBy(descending: Boolean = false, selector: (T) -> R?): List<T> {
return if (descending) sortedByDescending(selector) else sortedBy(selector)
}
listOf(3, 1, 4).sortedBy(true) { it }
⇒ 4, 3, 1
loke
11/02/2024, 9:12 AMcompareTo
function by this value. This allows you to avoid an if
statement in the comparator which is faster (if you care about that).Joffrey
11/02/2024, 9:16 AMif
statement in the comparator in the above approaches. The if
only runs once, and then all elements are processed, just like the if
that would set the 1 / -1 value. The -1 approach also add a multiplication for each element, if we're splitting hair. But anyway these considerations are most likely pointless.loke
11/02/2024, 9:19 AMcompareTo
method always returns an integer when comparing two objects. regardless of type.loke
11/02/2024, 9:20 AMJoffrey
11/02/2024, 9:21 AMsortedBy
function, not compareTo
ephemient
11/02/2024, 9:22 AMInt.MIN_VALUE
Joffrey
11/02/2024, 9:22 AMcompareTo
by hand I fail to see how this would be an improvement in terms of conciseness/ styleloke
11/02/2024, 9:26 AM