在 kotlin 中使用比较器

Abr*_*rge 2 collections comparator kotlin

我是 kotlin 的新手,如何使用 Collections

Collections.sort(list,myCustomComparator)
Run Code Online (Sandbox Code Playgroud)

我们如何MyCustomComparator在 kotlin 中编写方法?

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;
        } 
    };
Run Code Online (Sandbox Code Playgroud)

Ale*_*ger 7

这可以通过与 Java 几乎相同的方式完成:

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

if else if else ...被单个 Kotlin 取代when,以提高代码的可读性。

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

val customObjects = listOf(CustomObject(), CustomObject())
customObjects.sortedWith(myCustomComparator)
Run Code Online (Sandbox Code Playgroud)


Abr*_*rge 1

考虑@Alexander 的答案后,代码可以写为

private val MyCustomComparator = Comparator<MyObject> { a, b ->
        when {
            a == null && b == null -> return@Comparator 0
            a == null -> return@Comparator -1
            b == null -> return@Comparator 1
          
            else -> return@Comparator 0
        }
    }
Run Code Online (Sandbox Code Playgroud)