Daniel Wu
Daniel Wu

Reputation: 6003

takeWhile: also need first element failed the condition in scala

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

What if I also need to include 5 in the result?

Upvotes: 3

Views: 1191

Answers (3)

wheaties
wheaties

Reputation: 35980

Edit

If this is not a parallelized computation and you won't be using the parallel collections:

var last = myList.head
val rem = myList.takeWhile{ x=>
  last = x
  x < 5
}

last :: rem

anonymous function forming a closure around the solution you want.

Previous Answer

I'd settle for the far less complicated:

.takeWhile(_ <= 5)

wherein you're just using the less than or equal operator.

Upvotes: 1

swaraj patil
swaraj patil

Reputation: 209

List(1,2,3,4,5,6,7,8).takeWhile(_ <= 5)

This is best optimal solution for it

Upvotes: -1

mohit
mohit

Reputation: 4999

Assuming that the function that you will be using is more complicated than the taking first 5 elements then,

You can do

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)

Also

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)

Also

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)

Upvotes: 4

Related Questions