Kotlin排序最后为空 [英] Kotlin sorting nulls last
问题描述
科特林将对象列表按可空字段排序为空的最后一种方式是什么?
What would be a Kotlin way of sorting list of objects by nullable field with nulls last?
排序的Kotlin对象:
Kotlin object to sort:
@JsonInclude(NON_NULL)
data class SomeObject(
val nullableField: String?
)
与下面的Java代码类似:
Analogue to below Java code:
@Test
public void name() {
List<SomeObject> sorted = Stream.of(new SomeObject("bbb"), new SomeObject(null), new SomeObject("aaa"))
.sorted(Comparator.comparing(SomeObject::getNullableField, Comparator.nullsLast(Comparator.naturalOrder())))
.collect(toList());
assertEquals("aaa", sorted.get(0).getNullableField());
assertNull(sorted.get(2).getNullableField());
}
@Getter
@AllArgsConstructor
private static class SomeObject {
private String nullableField;
}
推荐答案
You can use these functions from the kotlin.comparisons
package:
-
fun <T: Comparable<T>> nullsLast(): Comparator<T?>
,它构造了一个可比较的比较器,该比较器只将null
s放在所有非空值之后;
fun <T: Comparable<T>> nullsLast(): Comparator<T?>
, which constructs a comparator of something comparable that just putsnull
s after all not-null values;
fun <T, K> compareBy(comparator: Comparator<in K>, selector: (T) -> K): Comparator<T>
,它接受比较器和为比较器提供值的函数,将它们组合成新的比较器;
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;
这将使您创建一个比较器,该比较器通过将null
放在最后来对SomeObject
进行比较.然后,您可以简单地将比较器传递给
This will let you make a comparator that compares SomeObject
by nullableField
putting null
s 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)]
这篇关于Kotlin排序最后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!