Antonis Radz
Antonis Radz

Reputation: 3097

kotlin sort list of stings by startsWith()

Is there any way to sort a list by startsWith(), for example having list of string, doing search and all results that starts with query would be at the top of the list?

one way to do it is:

    val filteredList = list.filter { it.startsWith(query, true) } +
        list.filterNot { it.startsWith(query, true) }

but not seeing it efficient

Upvotes: 2

Views: 698

Answers (1)

Joffrey
Joffrey

Reputation: 37710

You can use sortedBy, it works on Boolean values, but false values are first:

val list = listOf("nope", "abc", "abcd", "bacon", "abba", "bob", "something")

val sorted = list.sortedBy { it.startsWith("ab", ignoreCase = true) }
println(sorted) // [nope, bacon, bob, something, abc, abcd, abba]

If you want true values first, you can use the ! operator inside sortedBy.

Note that if you need this 2 sublists independently as well, you can use partition instead of 2 calls to filter, so that each item is only tested once:

val list = listOf("nope", "abc", "abcd", "bacon", "abba", "bob", "something")

val (matchingItems, nonMatchingItems) = list.partition { it.startsWith("ab", ignoreCase = true) }

println(matchingItems) // [abc, abcd, abba]
println(nonMatchingItems) // [nope, bacon, bob, something]

Upvotes: 4

Related Questions