Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract elements from 4 lists in scala?

Tags:

scala

case class TargetClass(key: Any, value: Number, lowerBound: Double, upperBound: Double)

val keys: List[Any] = List("key1", "key2", "key3")
val values: List[Number] = List(1,2,3);
val lowerBounds: List[Double] = List(0.1, 0.2, 0.3)
val upperBounds: List[Double] = List(0.5, 0.6, 0.7)

Now I want to construct a List[TargetClass] to hold the 4 lists. Does anyone know how to do it efficiently? Is using for-loop to add elements one by one very inefficient?

I tried to use zipped, but it seems that this only applies for combining up to 3 lists.

Thank you very much!

like image 876
DarkZero Avatar asked Jan 26 '26 17:01

DarkZero


1 Answers

One approach:

keys.zipWithIndex.map {
  case (item,i)=> TargetClass(item,values(i),lowerBounds(i),upperBounds(i))
}

You may want to consider using the lift method to deal with case of lists being of unequal lengths (and thereby provide a default if keys is longer than any of the lists?)

I realise this doesn't address your question of efficiency. You could fairly easily run some tests on different approaches.

like image 72
wwkudu Avatar answered Jan 28 '26 08:01

wwkudu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!