Kotlin - filtering a list of objects by comparing to a list of properties

Viewed 22714

I have a class Person:

class Person(var fullName: String, var nickname: String, var age: Int)

In my code, at some point I have a List of Person objects, and a list of nicknames.

var people: List<Person> = listOf(
  Person("Adam Asshat", "dontinviteme", 21),
  Person("Bob Bowyer", "bob", 37),
  Person("Emily Eden", "emily", 22)
)

var invitedToParty: List<String> = listOf("bob", "emily")

Now I want to get a List with only Bob and Emily by using lambda's, but I'm not sure how I'd go about it in Kotlin.

var invitedPeople: List<Person> = // a lambda that results in a list containing only Bob and Emily's objects

In C# I'd probably use LINQ and a .where()-method combined with an == any() but Kotlin doesn't seem to have anything like that from what I've found.

Is this even possible in Kotlin lambda's?

3 Answers

In C# you'd do:

people.Where(p => invitedToParty.Any(s => s == p.nickname));

Likewise in Kotlin, you'd use filter which is like Where and any speaks for it self:

people.filter { p -> invitedToParty.any { it == p.nickname } }

or using contains:

people.filter { invitedToParty.contains(it.nickname) }

You can use the .filter() function to do this:

val invitedPeople: List<Person> = people.filter { it.nickname == "bob" || it.nickname == "emily" }

Or you can do this set-based:

val invitedPeople: List<Person> = people.filter { it.nickname in setOf("bob", "emily") }

You can do this:

val invitedPeople: List<Person> = people.filter { invitedToParty.contains(it.nickname) }
Related