Kotlin排序为空

时间:2016-11-25 09:51:46

标签: sorting kotlin

Kotlin以可空字段排序对象列表的方法是什么?

要排序的Kotlin对象:

@JsonInclude(NON_NULL)
data class SomeObject(
    val nullableField: String?
)

类似于以下Java代码:

@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;
}

3 个答案:

答案 0 :(得分:20)

您可以使用this包中的这些功能:

这样您就可以制作一个比较器,将最后SomeObject nullableFieldnull进行比较。然后你可以简单地将比较器传递给
fun <T, K> compareBy(comparator: Comparator<in K>, selector: (T) -> K): Comparator<T>,它使用比较器将一个iterable分类到一个列表中:

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

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

答案 1 :(得分:13)

您可以使用compareBy并传递nullsLast作为比较器,如下所示:

val elements = listOf(SomeObject("bbb"), SomeObject(null), SomeObject("aaa"))

val sorted = elements.sortedWith(compareBy<SomeObject,String?>(nullsLast(), { it.name }))

println(sorted) //-> [SomeObject(name=aaa), SomeObject(name=bbb), SomeObject(name=null)]

答案 2 :(得分:2)

您可以使用nullsLast并将compareBy用作比较器,如下所示:

val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")

sortedValues.sortWith(nullsLast(compareBy { it.second }))

println(sortedValues)