I have 3 vals, each of type Array[String]
they are all equal in length
val1.length == val2.length // true
Next, I created a case class as following:
case class resource(name: String, count: Int, location: String)
I want to create a list, a List[resource]
such that each object of this list is created from the corresponding elements of the val
s, i.e, val1
, val2
, val3
Something like this:
val newList: List[resource] = (val1(0), val2(0).toInt, val3(0)),
(val1(1), val2(1).toInt, val3(1)),
...
(val1(val1.length), val2(val2.length).toInt, val3(val3.length)
I'm not sure how to proceed. Do I use flatMap, foreach, for-loops, or something else?
The idea is to create this abovementioned newList
and compare it to the result obtained from a SQL database using doobie.
val comparator = sql"sql statment".query[resource]
comparator.to[List].transact(xa).unsafeRunSync()
You can zip your arrays, which combines the corresponding elements of the zipped sequences into tuples, and them map
the resource.apply
method over the combined sequence:
val val1: Array[String] = Array("name 1", "name 2", "name 3")
val val2: Array[String] = Array("1", "2", "3")
val val3: Array[String] = Array("loc 1", "loc 2", "loc 3")
scala> (val1, val2.map(_.toInt), val3).zipped.map(resource)
res1: Array[resource] = Array(resource(name 1,1,loc 1), resource(name 2,2,loc 2), resource(name 3,3,loc 3))
You can then convert this Array
to List
if needed:
scala> (val1, val2.map(_.toInt), val3).zipped.map(resource).toList
res2: List[resource] = List(resource(name 1,1,loc 1), resource(name 2,2,loc 2), resource(name 3,3,loc 3))