什么是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;
}

推荐答案

您可以使用kotlin.comparisons软件包中的以下函数:

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相关问答推荐

Spring Boot Bean验证器未触发

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

如何在Android应用判断上运行多个查询

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

Kotlin中是否可以混合使用推断和显式的通用类型参数?

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

generic 类实例列表 - 调用采用 T 的函数

使用 Jetpack Compose 使用参数导航

多个不同的指针输入

从带有 Room 和 Flows 的 SQLite 表中获取祖先树

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

从列表中的每个对象中 Select 属性

如何使用 Coil 从 URL 获取位图?

无法创建类 ViewModel kotlin 的实例

如何通过反射使用 Kotlin 对象

为什么 Kotlin Pair 中的条目不可变?

kotlin-bom 库是做什么的?

RecyclerView SnapHelper无法显示第一个/最后一个元素

从命令行运行Java到Kotlin转换器?

Kotlin替换字符串中的多个单词