Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I filter a set to another set in Kotlin

Tags:

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" }
like image 647
gringogordo Avatar asked Nov 06 '18 15:11

gringogordo


1 Answers

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

allPets.filterTo(HashSet()) { pet -> pet.name != "Bob" }
like image 146
yole Avatar answered Oct 14 '22 23:10

yole