Ipkiss
Ipkiss

Reputation: 801

How can I rewrite this Kotlin filter method more succinctly?

I have a list of strings. I want to search given a query string and say I only want the first 10 matching strings. Here is what I tried, the first one does exactly what I want.

I was wondering if there is a succinct way of writing it.

fun search(query: String): ArrayList<String> {
    val found = ArrayList<String>()
    for (i in terms.indices) {
        if (terms[i].contains(query)) {
            found.add(terms[i])
        }
        if (found.size == 10) {
            break
        }
    }
    return found
}

I wanted to use this one but as you can see this is not as efficient as the above one because it goes through the whole list

fun search2(query: String): List<String> {
    return terms.filter { it.contains(query) }.take(10)
}

Upvotes: 1

Views: 102

Answers (1)

al3c
al3c

Reputation: 1452

Using a sequence should give you what you want:

fun search2(query: String): List<String> {
    return terms.asSequence().filter { it.contains(query) }.take(10).toList()
}

You might not need the toList if you're fine with keeping a sequence as result.

Upvotes: 6

Related Questions