Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 329
The Fox Avatar asked Dec 27 '18 23:12

The Fox


2 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) }
like image 175
Ousmane D. Avatar answered Sep 20 '22 11:09

Ousmane D.


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") }
like image 25
Todd Avatar answered Sep 18 '22 11:09

Todd