Search code examples
kotlincollectionscomparator

Using comparator in kotlin


I'm new to kotlin, how to compare objects using Collections

Collections.sort(list,myCustomComparator)

How can we write a MyCustomComparator method in 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;
        } 
    };


Solution

  • After considering the @Alexander answer, the code can be written as

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