Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala have any collections that sort by value instead of key?

Tags:

scala

For example the following code produces the order Stock1, Stock2, Stock3

var tm = TreeMap("Stock1" -> 4.2, "Stock3" -> 3.7, "Stock2" -> 5.9)

What I'm looking for is a collection or technique that can produce the following

Stock2, Stock1, Stock3 which represents the prices in descending order

like image 518
deltanovember Avatar asked Aug 06 '11 22:08

deltanovember


People also ask

Is Scala list ordered?

In Scala we do not sort Lists in-place. They are immutable. But we use lambda expressions, and the Ordering type, to create sorted copies of these lists.

What is Scala mapValues?

mapValues creates a Map with the same keys from this Map but transforming each key's value using the function f .

Is Scala map ordered?

Solution. Scala has a wealth of map types to choose from, and you can even use Java map classes. If you're looking for a basic map class, where sorting or insertion order doesn't matter, you can either choose the default, immutable Map , or import the mutable Map , as shown in the previous recipe.


2 Answers

scala> val sorted1 = tm.toList.sortBy (_._2)                                                           
sorted1: List[(java.lang.String, Double)] = List((Stock3,3.7), (Stock1,4.2), (Stock2,5.9))

scala> val sorted2 = tm.toList.sortBy (_._1)
sorted2: List[(java.lang.String, Double)] = List((Stock1,4.2), (Stock2,5.9), (Stock3,3.7))

Revert sorted1, to get it descending, or sortWith:

scala> val sorted3 = tm.toList.sortWith (_._2 > _._2) 
sorted3: List[(java.lang.String, Double)] = List((Stock2,5.9), (Stock1,4.2), (Stock3,3.7))

Version 4, sort by -x (minus x):

scala> val sorted4 = tm.toList.sortBy (-_._2)   
sorted4: List[(java.lang.String, Double)] = List((Stock2,5.9), (Stock1,4.2), (Stock3,3.7))
like image 109
user unknown Avatar answered Oct 19 '22 17:10

user unknown


I don't think there is a built-in collection that keeps the map sorted by value so that you can read out the sorted values in linear time, but how to sort a scala.collection.Map[java.lang.String, Int] by its values? shows ways to get the entries out sorted by value.

like image 35
Ray Toal Avatar answered Oct 19 '22 15:10

Ray Toal