Logo

dev-resources.site

for different kinds of informations.

Android Sorting CheatSheet

Published at
5/13/2020
Categories
sorting
android
java8
kotlin
Author
Aniket Kadam
Categories
4 categories in total
sorting
open
android
open
java8
open
kotlin
open
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()
}

Featured ones: