Reputation: 11942
What is the most efficient way to create a Set from a string like this
val string = "Set(1,3,3,4,5)"
val mySet = string.toSet[Int]
res0: Set[Int] = Set(1,3,4,5)
I want to create this toSet
method.
Upvotes: 0
Views: 1749
Reputation: 52681
implicit class StringWithToIntSet(val self: String) extends AnyVal {
def toIntSet: Set[Int] = {
val Re = """Set\((.*)\)""".r
self match {
case Re(inner) => inner.split(",").map(_.toInt).toSet
}
}
}
Then:
scala> "Set(1,3,3,4,5)".toIntSet
res0: Set[Int] = Set(1, 3, 4, 5)
Note:
toSet
because String
already has a toSet
method (that creates a Set[Char]
)Upvotes: 5