1

I have a file like this:

1    4.146846
2    3.201141
3    3.016736
4    2.729412

I want to use toDouble but, it's not working as expected :

val rows = textFile.map { line =>  
     val fields = line.split("[^\\d]+") 
     ((fields(0),fields(1).toDouble))     
}

val Num = rows.sortBy(- _._2).map{case (user , num) => num}.collect.mkString("::")

println(Num)

The result print out is 4.0::3.0::3.0::2.0.
What I expect is 4.146846::3.201141::3.016736::2.729412

How do I do this?

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
user2492364
  • 6,543
  • 22
  • 77
  • 147

2 Answers2

4

Your regular expression is stopping at the decimal point in 4.146846.

Try line.split("[^\\d.]+")

millhouse
  • 9,817
  • 4
  • 32
  • 40
0

What about splitting the lines by variant number of whitespaces? The regular expression would be like '[\s]+' . This resumes in two parts per line, one digit and one double string.

My whole program looks like:

object Application {
  def parseDouble(s: String) = 
    try { 
      Some(s.toDouble) 
    } catch { 
      case _ => None 
    }

  def main(args: Array[String]): Unit = {
    val linesIt = "1    3.201141\n2    4.146846\n3    3.016736\n4    2.729412".lines
    var doubles: List[Double] = List.empty
    for (singleLine <- linesIt) {
      val oneDouble = parseDouble(singleLine.split("[\\s]+")(1))
      doubles = if (oneDouble != None) 
        oneDouble.get::doubles
      else
        doubles
    }
    val doublesArr = doubles.toArray
    println("before sorting: " + doublesArr.mkString("::"))
    scala.util.Sorting.quickSort(doublesArr)
    println("after sorting: " + doublesArr.mkString("::"))
  }
}
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
oRUMOo
  • 153
  • 1
  • 2
  • 11