gringogordo
gringogordo

Reputation: 2130

How should I filter a set to another set in Kotlin

I am trying to get to grips with Kotlin and functional programming and failing on a pretty simple exercise.

I'll modify this a little so as to make it not too obvious that it is from a specific online course but I'm just trying to get started really and not trying to fool anyone...

I am working with 2 collections

data class Pet(val name: String)

data class Household (
   val pet: Pet,
   ... 
)

data class District(
   val allPets: Set<Pet>,
   val allHouseholds: List<Household>,
   ...)

I want to find all pets not in a household. It has to be returned as a Set as I have been given this signature to play with

fun Locality.findFeralPets(): Set<Pet> =

I was going to do a filter operation but this returns a list and I can't see how to convert this to a set. Can anyone point me in the right direction ? It is very possible that filter is the wrong approach altogether!

allPets.filter { pet -> pet.name != "Bob" }

Upvotes: 9

Views: 3307

Answers (2)

yole
yole

Reputation: 97148

It's more efficient to do this in a different way, avoiding a separate conversion:

allPets.filterTo(HashSet()) { pet -> pet.name != "Bob" }

Upvotes: 16

Yoni Gibbs
Yoni Gibbs

Reputation: 7018

filter returns an Iterable which has an extension method on it called toSet which returns a Set. e.g.

allPets.filter { pet -> pet.name != "Bob" }.toSet()

Upvotes: 3

Related Questions