Stop processing maps in Scala

后端 未结 1 1237
既然无缘
既然无缘 2021-01-25 23:54

In the following code, I need to stop processing the map if the element = 2:

val seq = Seq(1,2,3)

seq.map { x => if (x==2) /* stop processing the map */  }
<         


        
相关标签:
1条回答
  • 2021-01-26 00:27

    You can't do it with map() directly as map() is designed to work over the entire collection, but you can split the collection into 2 parts and apply the map() to one and not the other.

    val seq = Seq(0,1,2,3,3,2,1,0)
    val (before, after) = seq.span(_ != 2)
    before.map(_ + 70) ++ after  //res0: Seq[Int] = List(70, 71, 2, 3, 3, 2, 1, 0)
    
    0 讨论(0)
提交回复
热议问题