Jethro
Jethro

Reputation: 3329

scala: Create a Sequence of tuples with a constant key

Given a constant value and a potentially long Sequence:

   a:String = "A"
   bs = List(1, 2, 3)

How can you most efficiently construct a Sequence of tuples with the first element equalling a?

Seq(
    ( "A", 1 ),
    ( "A", 2 ),
    ( "A", 3 )
)

Upvotes: 1

Views: 3017

Answers (3)

MilanRegmi
MilanRegmi

Reputation: 519

You can do it using map just like in the answer provided by @Pedro or you can use for and yield as below:

val list = List(1,2,3)
 val tuple = for {
    i <- list
  } yield ("A",i)
  println(tuple)

Output:

List((A,1), (A,2), (A,3))

You are also asking about the efficient way in your question. Different developers have different opinions between the efficiency of for and map. So, I guess going through the links below gives you more knowledge about the efficiency part.

for vs map in functional programming

Scala style: for vs foreach, filter, map and others

Getting the desugared part of a Scala for/comprehension expression?

Upvotes: 1

Volty De Qua
Volty De Qua

Reputation: 290

Since the most efficient would be to pass (to further receiver) just the seq, and the receiver tuple the elements there, I'd do it with views.

val first = "A"
val bs = (1 to 1000000).view
further( bs.map((first, _)) )

Upvotes: 1

Pedro Correia Lu&#237;s
Pedro Correia Lu&#237;s

Reputation: 1095

Just use a map:

val list = List(1,2,3)

list.map(("A",_))

Output:

res0: List[(String, Int)] = List((A,1), (A,2), (A,3))

Upvotes: 4

Related Questions