Count number of Strings that can be converted to Int in a List

This is a bit shorter:

myList.count(x => Try(x.toInt).isSuccess)

Note that this solution will handle any string that can be converted to integer via .toInt, including negative numbers.


You may consider string.matches method with regex as well, to match only positive integers:

val myList = List("7842", "abf45", "abd", "-56")
// myList: List[String] = List(7842, abf45, abd, -56)

myList.count(_.matches("\\d+"))
// res18: Int = 1

If negative integers need to be counted (and take into account possible +/- signs):

myList.count(_.matches("[+-]?\\d+"))
// res17: Int = 2

I would caution against using exception handling (like Try) in control flow -- it's very slow.

Here's a solution that uses idiomatic Scala collection operations, performs well, and will not count negative numbers:

scala> val myList = List("7842", "abf45", "abd", "56")
myList: List[String] = List(7842, abf45, abd, 56)

scala> myList.count(_.forall(_.isDigit)) 
res8: Int = 2

EDIT: @immibis pointed out that this won't detect strings of numbers that exceed Integer.MaxValue. If this is a concern, I would recommend one of the following approaches:

import scala.util.Try
myList.count(x => Try(x.toInt).filter(_ >= 0).isSuccess)

or, if you want to keep the performance of my first answer while still handling this edge case:

import scala.util.Try
myList.count(x => x.forall(_.isDigit) && Try(x.toInt).filter(_ >= 0).isSuccess)

Tags:

Scala