Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Find matching objects in array

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!

like image 310
Noname135 Avatar asked Dec 20 '18 12:12

Noname135


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.

like image 76
Adam Avatar answered Oct 06 '22 08:10

Adam