I have a string that looks like the following:
"1,100,53,5000,23,3,3,4,5,5"
I want to simply turn this into a Array of distinct Integer elements. Something that would look like:
Array(1, 100, 53, 5000, 23, 3, 4, 5)
Is there a String
method in Scala that would help with this?
scala> "1,100,53,5000,23,3,3,4,5,5".split(",").map(_.toInt).distinct
res1: Array[Int] = Array(1, 100, 53, 5000, 23, 3, 4, 5)
Obviously this raises an exception if one of the value in the array isn't an integer.
edit: Hadn't seen the 'distinct numbers only' part, fixed my answer.
Another version that deals nicely with non parseable values and just ignores them.
scala> "1,100,53,5000,will-not-fail,23,3,3,4,5,5".split(",").flatMap(maybeInt =>
scala.util.Try(maybeInt.toInt).toOption).distinct
res2: Array[Int] = Array(1, 100, 53, 5000, 23, 3, 4, 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With