DEV Community

Aniket Kadam
Aniket Kadam

Posted on

Android Sorting CheatSheet

For Kotlin

If there's just one value to compare, then the following can be used

    names.sortedBy{ it.length }

The two methods are used to compare the items in the list. If the first one returns equal, then the second will take over

fun arrangeNames(names: List<String>): List<String> {
    names.sortedWith(compareBy({it.length}, {it.length}))
}

For Java

When using java, a comparator object has to be created, these can be chained with thenBy calls.
A stream still needs to be created and collected for the result to be calculated.

public List<String> arrangeNames(List<String> names) {
    Comparator<String> sizeComparator = Comparator.comparing(String::length).thenBy(String::length)
    return names.stream().sorted(sizeComparator).collect()
}

Top comments (0)