-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.

6
  • possible duplicate of How do I sort an array in Scala? Another dupe or close to: stackoverflow.com/questions/9751434/… Commented Jul 4, 2014 at 20:44
  • 6
    I don't think you can honestly say you've researched this question before posting. Commented Jul 4, 2014 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 Commented Jul 4, 2014 at 20:54
  • 5
    l.split("\\s").map{_.toDouble}.sorted Commented Jul 4, 2014 at 21:09
  • 4
    List(Double) should be List[Double](). List(Double) is a list holding the companion object for Double. Commented Jul 5, 2014 at 2:39

1 Answer 1

2

Use the sorted method

dubs.sorted  // List(1.3, 2.3, 3.2, 4.5)
Sign up to request clarification or add additional context in comments.

1 Comment

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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.