在 kotlin 中使用比较器

2024-03-20

我是 kotlin 新手,如何使用比较对象Collections

Collections.sort(list,myCustomComparator)

我们怎样才能写一个MyCustomComparator科特林中的方法?

private final Comparator<CustomObject> myCustomComparator = (a, b) -> {
        if (a == null && b == null) {
            return 0;
        } else if (a == null) {
            return -1;
        } else if (b == null) {
            return 1;
        } 
    };

这几乎可以用与 Java 中相同的方式完成:

private val myCustomComparator =  Comparator<CustomObject> { a, b ->
    when {
        (a == null && b == null) -> 0
        (a == null) -> -1
        else -> 1
    }
}

if else if else ...被单个 Kotlin 取代when为了使代码更好的可读性。

在 Kotlin 中使用 a 对列表进行排序Comparator也可以这样写:

val customObjects = listOf(CustomObject(), CustomObject())
customObjects.sortedWith(myCustomComparator)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 kotlin 中使用比较器 的相关文章

随机推荐