NiceOneMoney
NiceOneMoney

Reputation: 169

How to filter elements from a sublist of objects in scala?

I have a list of objects[T], each of which has another list of objects[M]. I would like to filter out the inner list M given value for comparison.

Here is an example of such List:

case class People(val name: String, val pets: List[Pet])

case class Pet(val name: String, val `type`: String)

val noisyNeighbors = List(
  People(
    "Obelix", 
    List(
      Pet("koko", "cat"),
      Pet("kiki", "dog")
    )
  ),
  People(
    "Asterix", 
    List(
      Pet("piki", "lizard"),
      Pet("poko", "dog")
    )
  )
)

Given a val petTypeToRemove = "dog", I would like to have a result list of:

val lessNoisyNeighbors = List(
  People(
    "Obelix", 
    List(
      Pet("koko", "cat")
    )
  ),
  People(
    "Asterix", 
    List(
      Pet("piki", "lizard")
    )
  )
)

I have tried a few things, but I don't really know where to start:

val lessNoisyNeighbors = noisyNeighbors.filter {
  ???
}

Upvotes: 1

Views: 1185

Answers (2)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

Call map on the List of neighbors, and for every neighbor, replace it with a copy that has pets of the specified type filtered out. Note that nothing here is mutated.

val petTypeToRemove = "dog"

val lessNoisyNeighbors =
  noisyNeighbors.map(n => n.copy(pets = n.pets.filterNot(_.`type` == petTypeToRemove)))

Upvotes: 1

Levi Ramsey
Levi Ramsey

Reputation: 20591

You don't want to filter the neighbors (from how you want to handle Asterix).

val lessNoisyNeighbors = noisyNeighbors.map { neighbor =>
  neighbor.copy(pets = neighbor.pets.filter(_ != petTypeToRemove))
}

Some embellishment from there might be needed (e.g. to preserve reference equality where possible, or to remove someone whose only pet is a pet to remove), but that's the basic skeleton.

Upvotes: 0

Related Questions