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" }
It's more efficient to do this in a different way, avoiding a separate conversion:
allPets.filterTo(HashSet()) { pet -> pet.name != "Bob" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With