Scala for loop over two lists simultaneously

后端 未结 1 1378
旧巷少年郎
旧巷少年郎 2020-12-25 10:58

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

相关标签:
1条回答
  • 2020-12-25 11:17

    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.

    0 讨论(0)
提交回复
热议问题