8

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 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Or, even shorter: val filtered = locales.filter{ it.language in lang }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.