Kotlin排序最后为空 [英] Kotlin sorting nulls last

查看:104
本文介绍了Kotlin排序最后为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

科特林将对象列表按可空字段排序为空的最后一种方式是什么?

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?>, 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> ,它接受比较器和为比较器提供值的函数,将它们组合成新的比较器;

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 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)]

这篇关于Kotlin排序最后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆