-1

How do I sort a simple list of Doubles in Scala?

var dubs = List(1.3,4.5,2.3,3.2)

I think my question may not have accurately reflected my specific problem, since I realize now that dubs.sorted will work just fine for the above. My problem is as follows, I have a string of doubles "2.3 32.4 54.2 1.33" that I'm parsing and adding to a list

var numsAsStrings = l.split("\\s");
var x = List(Double);
var i = 0;
for( i <- 0 until numsAsStrings.length) {
  x :+ numsAsStrings(i).toDouble;
}

So, I would think that I could just call x.sorted on the above, but that doesn't work... I've been looking over the sortBy, sorted, and sortWith documentation and various posts, but I thought the solution should be simpler. I think I'm missing something basic, regardless.

kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Gary Sharpe
  • 2,369
  • 8
  • 30
  • 51
  • possible duplicate of [How do I sort an array in Scala?](http://stackoverflow.com/questions/1131925/how-do-i-sort-an-array-in-scala) Another dupe or close to: http://stackoverflow.com/questions/9751434/simplest-way-to-sort-list-of-objects – Paul Sasik Jul 04 '14 at 20:44
  • 6
    I don't think you can honestly say you've researched this question before posting. – Michael Zajac Jul 04 '14 at 20:45
  • @LimbSoup. You're right in a way, especially given what I originally posted. I didn't accurately reflect my problem, though, which is my fault. dubs.sorted works just fine on what I listed as the first example. My problem may be equally trivial, but I can seem to find the easy solution I expected. I'v added more detail to the original question – Gary Sharpe Jul 04 '14 at 20:54
  • 5
    l.split("\\s").map{_.toDouble}.sorted – elm Jul 04 '14 at 21:09
  • 4
    `List(Double)` should be `List[Double]()`. `List(Double)` is a list holding the companion object for `Double`. – wingedsubmariner Jul 05 '14 at 02:39
  • "that doesn't work." Don't make us guess. In what way does it not work? – The Archetypal Paul Jul 05 '14 at 08:16

1 Answers1

2

Use the sorted method

dubs.sorted  // List(1.3, 2.3, 3.2, 4.5)
dhg
  • 52,383
  • 8
  • 123
  • 144
  • Thank you for answering the original question. This has become a bit of a cluster @#$%, since I believe my problem has more to do with lists than sorting... – Gary Sharpe Jul 04 '14 at 21:13