39

I have a List[Message] and a List[Author] which have the same number of items, and should be ordered so that at each index, the Message is from the Author.

I also have class that we'll call here SmartMessage, with a constructor taking 2 arguments: a Message and the corresponding Author.

What I want to do, is to create a List[SmartMessage], combining the data of the 2 simple lists.

Extra question: does List preserve insertion order in Scala? Just to make sure I create List[Message] and a List[Author] with same ordering.

1
  • 2
    zip will only suffice up to 3 lists. If you have more, you might like to look at this question / answer: stackoverflow.com/a/17072064/770361 Commented Jun 19, 2013 at 20:06

1 Answer 1

86

You could use zip:

val ms: List[Message] = ???
val as: List[Author] = ???

var sms = for ( (m, a) <- (ms zip as)) yield new SmartMessage(m, a)

If you don't like for-comprehensions you could use map:

var sms = (ms zip as).map{ case (m, a) => new SmartMessage(m, a)}

Method zip creates collection of pairs. In this case List[(Message, Author)].

You could also use zipped method on Tuple2 (and on Tuple3):

var sms = (ms, as).zipped.map{ (m, a) => new SmartMessage(m, a)}

As you can see you don't need pattern matching in map in this case.

Extra

List is Seq and Seq preserves order. See scala collections overview.

There are 3 main branches of collections: Seq, Set and Map.

  • Seq preserves order of elements.
  • Set contains no duplicate elements.
  • Map contains mappings from keys to values.

List in scala is linked list, so you should prepend elements to it, not append. See Performance Characteristics of scala collections.

Sign up to request clarification or add additional context in comments.

1 Comment

One thing to keep in mind when zipping a list with data together with an empty list is that the result will also be an empty list. So you might want to make sure your code is okay with that. Otherwise you could check for one of the lists being empty first or use zipAll() with default values.

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.