Kotlin - Find matching objects in array

Viewed 9504

Let's say I have an array of strings and I want to get a list with objects that match, such as:

var locales=Locale.getAvailableLocales()
val filtered = locales.filter { l-> l.language=="en" } 

except, instead of a single value I want to compare it with another list, like:

val lang = listOf("en", "fr", "es")

How do I do that? I'm looking for a one-liner solution without any loops. Thanks!

1 Answers

Like this

var locales = Locale.getAvailableLocales()
val filtered = locales.filter { l -> lang.contains(l.language)} 

As pointed out in comments, you can skip naming the parameter to the lambda, and use it keyword to have either of the following:

val filtered1 = locales.filter{ lang.contains(it.language) }
val filtered2 = locales.filter{ it.language in lang }

Just remember to have a suitable data structure for the languages, so that the contains() method has low time complexity like a Set.

Related