Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala turn comma delimited string to Array

Tags:

scala

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?

like image 589
randombits Avatar asked Nov 03 '13 01:11

randombits


2 Answers

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.

like image 95
Marth Avatar answered Oct 24 '22 12:10

Marth


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)
like image 25
kompot Avatar answered Oct 24 '22 11:10

kompot