flatMap将字符串列表添加到整数列表中

时间:2017-08-20 21:49:29

标签: scala

给出一个列表的字符串,例如:

val list = List("1", "2")

我可以轻松地将它们转换为整数列表:

list.map(_.toInt)

但是,如果字符串列表包含非整数,是否有办法在Scala中轻松填充它们?

例如:

val list = List("1", "2", "output")

使用上述map(_.toInt)会有例外情况:

  

java.lang.NumberFormatException:对于输入字符串:"输出"

我尝试使用flatMap,但它不会编译:

  

:13:错误:类型不匹配;
     发现:Int
     必需:scala.collection.GenTraversableOnce [?]

2 个答案:

答案 0 :(得分:2)

Try很好,但有时你想避免例外。

List("4","4g5","77").collect{case x if x.forall(_.isDigit) => x.toInt} 
//res0: List[Int] = List(4, 77)

答案 1 :(得分:0)

这是另一种解决方案:

val list: List[Char] = List('1', 'a', '2') 
list.filter(_.isDigit).map(_.asDigit.toInt)
相关问题