1

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 )
)
Jethro
  • 3,029
  • 3
  • 27
  • 56

3 Answers3

4

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))
MilanRegmi
  • 499
  • 3
  • 12
Pedro Correia Luís
  • 1,085
  • 6
  • 16
  • 2
    A quick note, if this collection is going to be transformed again, consider using `iterator`. – Luis Miguel Mejía Suárez Aug 12 '19 at 15:39
  • 1
    @LuisMiguelMejíaSuárez I disagree. For anything that doesn't require performance optimization (hundreds of thousands of elements, transformed continously) one should always go for the immutable approach - for the sole reason of code quality. – Markus Appel Aug 12 '19 at 15:48
  • The question is ideally asking for the most efficient approach. – Jethro Aug 12 '19 at 15:50
  • 2
    @Jethro I don't think there is a difference in efficiency wether a `List` or an `Iterator` is constructed. Only when it comes to transformation there might be. – Markus Appel Aug 12 '19 at 15:55
  • 2
    @MarkusAppel While I agree with you _(I would never expose an Iterator)_, the question asked about performance. I clearly stated that only if the collection is going to be transformed latter. - Now, I must agree I was very vague, let me rephrase myself: If you are going to perform **MULTIPLE & IMMEDIATE** transformations to the same collection, consider using `iterator` first and at the end, call one of the `to` methods to receive back an immutable collection with all changes applied at once. As a best practice, consider keeping all that in the scope of a method, private to the outside world. – Luis Miguel Mejía Suárez Aug 12 '19 at 16:04
1

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?

MilanRegmi
  • 499
  • 3
  • 12
1

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, _)) )
Volty De Qua
  • 199
  • 6