Johan Vergeer
Johan Vergeer

Reputation: 5568

Find all sentences that end with one of strings in array with Kotlin

I'm looking for a way to filter strings that end with one value from an array in Kotlin.

fun findStringsThatEndWith(sentences: List<String>, value: String) = sentences
    .filter { it.endsWith(value) }

This will allow me to filter all sentences that end with one value.

But what I would like to do is:

fun findStringsThatEndWith(sentences: List<String>, vararg value: String) = sentences
    .filter { it.endsWith(value // This won't work //) }

And when I do this, I will have to know how many values the vararg will hold.

fun findStringsThatEndWith(sentences: List<String>, vararg value: String) = sentences
    .filter { it.endsWith(value[0]) || it.endsWith(value[1]) }

Upvotes: 1

Views: 423

Answers (1)

Yoni Gibbs
Yoni Gibbs

Reputation: 7018

In the lambda you pass to filter add a function that loops round the value parameter and checks each one, e.g.

fun findStringsThatEndWith(sentences: List<String>, vararg value: String) =
        sentences.filter { sentence -> value.any { sentence.endsWith(it) } }

Upvotes: 4

Related Questions