Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional programming: Get list of data from nested loop

I have three class

class C {
  var id: String = _
}

class B {
  var c: List[C] = _
}

class A {
  var b: List[B] = _
}

I want to collect all "id" of class "C" instance, which are in a class "A" instance

val c1 = new C
c1.id = "data1"
val c2 = new C
c2.id = "data2"

val b = new B
b.c = c1::c2::Nil

val a = new A
a.b = b::Nil

Expected output for this sample code is List[String] having two element (ie, data1, data2) In imperative programming, I have achieved same with below code snippet

def collectCId(a: A): List[String] = {
  var collect = List[String]()
  for(tmpb <- a.b){
    for(tmpc <- tmpb.c){
      collect = tmpc.id :: collect
    }
  }
  collect
}

How can I achieve same in functional way?

Scala Version: 2.11

like image 285
user811602 Avatar asked Feb 01 '26 23:02

user811602


1 Answers

With a for-comprehension:

def collectCId(a: A): List[String] = 
 for { 
   b <- a.b
   c <- b.c
 } yield c.id
like image 87
Chirlo Avatar answered Feb 04 '26 01:02

Chirlo