12

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?

4 Answers 4

20
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.

Sign up to request clarification or add additional context in comments.

Comments

8

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)

Comments

2

added type checking for the string being parseable as Int :

package load.data

object SplitArray {

  def splitArrayintoString(s: String): Set[Int] =
    {
      val strArray = s.split(",")
      strArray filter isParseAbleAsInt map (_.toInt) toSet
    }

  private def isParseAbleAsInt(str: String): Boolean =
    str.forall(Character.isDigit(_))

}

Comments

2

Starting Scala 2.13, if you expect items that can't be cast, you might want to use String::toIntOption in order to safely cast these split Strings to Option[Int]s and eliminate them with a flatMap:

"1,100,53s,5000,4,5,5".split(',').flatMap(_.toIntOption).distinct
// Array[Int] = Array(1, 100, 5000, 4, 5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.