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 )
)

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

5 Comments

A quick note, if this collection is going to be transformed again, consider using iterator.
@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.
The question is ideally asking for the most efficient approach.
@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.
@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.
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, _)) )

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.