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

17,414

Solution 1

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) }

Solution 2

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") }
Share:
17,414
The Fox
Author by

The Fox

Updated on June 03, 2022

Comments

  • The Fox
    The Fox almost 2 years

    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?

  • Joffrey
    Joffrey over 5 years
    Why not simply people.filter { invitedToParty.contains(it.nickname) }?
  • Ousmane D.
    Ousmane D. over 5 years
    @Joffrey I guess one could do that as well. updated to accommodate your comment.
  • Joffrey
    Joffrey over 5 years
    Thanks, in fact, I just realized there is more idiomatic in kotlin with the in operator: people.filter { it.nickname in invitedToParty }
  • Ousmane D.
    Ousmane D. over 5 years
    @Joffrey agreed, there are definitely several ways to go about this, I just thought I'd show the filter + any approach since that is the one OP is familiar with in C#. nevertheless, it's good to be suggested better solutions indeed. thanks!
  • The Fox
    The Fox over 5 years
    Thanks for your suggestions, Aomine and Joffrey. I'm always happy to learn multiple ways to accomplish something, I'll be trying this out as soon as I get back to my home laptop and then accept your answer.
  • The Fox
    The Fox over 5 years
    Set-based seems most appropriate for my purposes; your first approach is hard-coded, which isn't what I need for my actual problem. Thank you
  • Blundell
    Blundell about 4 years
    any is the most flexible when it as the main object is not what you need but a parameter of it i.e. it.nickname == p.nickname