0

I have a set of strings that look like:

"user-123"
"user-498"
"user-9891"

I want to return a set of integers like this:

123
498
9891

I can do this:

val mySet = // ....

mySet.map(x => x.replace("user-").toInt)

But if the toInt parsing fails it will crash, what would be a safer way to do this?

4 Answers 4

2

To ignore failed strings:

mySet.flatMap(s => Try(s.replace("user-", "").toInt).toOption)
Sign up to request clarification or add additional context in comments.

Comments

0

Use the isDigit()

Try("user-1234".toCharArray.filter(_.isDigit) .foldLeft("")((a, b) => a + b).toInt) .getOrElse(0)

Comments

0

You can use simple regular expression to only keep the numerical values.

Something like this:

val mySet = Seq("user-123","user-498","user-9891")
mySet.map(_.replaceAll("[^\\d]", ""))

Comments

0

You could check for strings that will successfully convert to an Int:

mySet.map(_.stripPrefix("user-")).collect { case x if x.forall(_.isDigit) => x.toInt }

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.