Search code examples
scalafunctional-programmingscala-3

Extracting an object from a nested list of objects


I have a problem that I have created a smaller version of.

I have a list of objects of type A lets call that L

L = List[A]

In A there is another list of objects B which have a property X.

To collect all A that have a B with X equaling V

L.filter(x => x.B.exists(y => y.X == V)).map(a => a.B)

Example code from REPL

class B(val X:Int){
  override def toString =
    s"b:$X"
}

class A(val b: List[B]) {
  override def toString =
    s"a: $b"
}

val listA1 = List(new B(1), new B(2), new B(3))
val listA2 = List(new B(1), new B(7), new B(12))
val listA3 = List(new B(9), new B(5), new B(3))

val L = List(new A(listA1), new A(listA2), new A(listA3))

println(L) // List(a: List(b:1, b:2, b:3), a: List(b:1, b:7, b:12), a: List(b:9, b:5, b:3))

val res = L.filter(x => x.b.exists(y => y.X == 3)).map(a => a.b)

println(res) // List(List(b:1, b:2, b:3), List(b:9, b:5, b:3))

Now the problem - How to get a list of the B objects whose X value is 3?

That is a list as follows

List(b:3, b:3)

In the real world I am after other attributes of B but first I need to get the B's.


Solution

  • If I understand your request, this is all you need.

    L.flatMap(_.b.filter(_.X == 3))
    

    BTW, your use upper/lower-case variable names is inconsistent, haphazard, and rather confusing.