scala - takeWhile : also need first element failed the condition in scala

标签 scala

scala> List(1,2,3,4,5,6,7).takeWhile(i=>i<5) 
res1: List[Int] = List(1, 2, 3, 4)

如果我还需要在结果中包含 5 怎么办?

最佳答案

假设你将要使用的函数比取前 5 个元素更复杂,

你可以做到

scala> List(1,2,3,4,5,6,7)
res5: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

scala> res5.takeWhile(_<5) ++ res5.dropWhile(_<5).take(1)
res7: List[Int] = List(1, 2, 3, 4, 5)

还有

scala> res5.span(_<5)
res8: (List[Int], List[Int]) = (List(1, 2, 3, 4),List(5, 6, 7))
scala> res8._1 ++ res8._2.take(1)
res10: List[Int] = List(1, 2, 3, 4, 5)

还有

scala> res5.take(res5.segmentLength(_<5, 0) + 1)
res17: List[Int] = List(1, 2, 3, 4, 5)

scala> res5.take(res5.indexWhere(_>5))
res18: List[Int] = List(1, 2, 3, 4, 5)

关于scala - takeWhile : also need first element failed the condition in scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828190/

相关文章:

java - 如何使用kafka流处理 block /批处理数据?

scala - 为什么使用函数参数应用 println 会失败而不打印?

java - 使用WindowBuilder + Scala,有什么好的想法吗?

scala - def foo[A,B] 到底是什么意思?类型阴影

由于我使用依赖注入(inject),Scala play 2.5 测试未运行

scala - 如何在Spark中处理多行输入记录

java - Riak:通过 Java/Scala 在键上创建索引

scala - Actors模型(Scala,Erlang)最适合​​哪种应用程序/服务/组件?

sbt 发布的工件中的 scala-library.jar 版本

scala - 如何在 Scala 中实现由数组支持的不可变 IndexedSeq