Reputation: 801
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