Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Scala for loop over two lists simultaneously

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.

question from:https://stackoverflow.com/questions/17199534/scala-for-loop-over-two-lists-simultaneously

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...