I have a string 1,3,5-10
and I have to convert this string into a list of integer in scala.
The list will like this --->>. List(1,3,5,6,7,8,9,10)
How will be the best way to convert a string list into an integer list using flatMap
.
or What will the minimal line of code in Scala to do this.
This is the code I have tried to achieve it but I wanted a better way to do so
val selectedNumberList: mutable.MutableList[Int] = mutable.MutableList[Int]()
val numbersList = "1,3,5-10".split(",").toList
for(i <- 0 until numbersList.size ){
if(numbersList(i).contains("-")){
val splitNumberToList = numbersList(i).split("-").toList
for(j <- splitNumberToList.head.toInt to splitNumberToList.last.toInt){
selectedNumberList += j
}
}else{
selectedNumberList += numbersList(i).toInt
}
}
The above code does not use the flat map but can we do this in a better way.