Reputation: 23
I need to create a new vector from Vector("lumber", "stone", "magic potion","stone","lumber")
but without the string "lumber"
, if i use the method filterNot(_=="lumber")
it removes the two elements that match "lumber"
. is there a filter out just one ocurrence?
i tried using .distinct
but i need the two stones in the vector.
Upvotes: 2
Views: 129
Reputation: 15294
Easiest way is to use diff:
val c = Vector("lumber", "stone", "magic potion","stone","lumber")
c diff Vector("lumber")
// result: Vector(stone, magic potion, stone, lumber)
Upvotes: 2
Reputation: 34423
You can split the collection at the first occurence and then drop it:
val (pre, post) = c.span(_ == "lumber")
pre.dropRight(1) ++ post
When there is no "lumber" in the collection, pre
will be empty and pre.dropRight(1)
will drop nothing.
With 2.13 you can prefer a one-liner using pipe
:
import scala.util.chaining._
c.span(_ == "lumber").pipe(split => split._1.dropRight(1) ++ split._2)
Upvotes: 1