Home > Software engineering >  Extracting an object from a list of objects in a object that itself is in a list of objects Using SC
Extracting an object from a list of objects in a object that itself is in a list of objects Using SC

Time:12-03

I have a problem which is defeating me in many ways. Too complex for my poor little brain to explain so I have created an abstract version.

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 B with X == to 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 with the X value 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.

CodePudding user response:

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.

  • Related