Does Scala have any collections that sort by value instead of key?
For example the following code p开发者_StackOverflow社区roduces 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
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))
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.
The problem here is that you look up by key, so there's no use in sorting by value -- you'll still have to keep track of the keys somehow.
Consider, for instance, a LinkedHashMap
sorted by value. It finds the key through the hash table, and iterates using the linked list. Unfortunately, it requires O(n)
insertion, because it has to iterates through the list to find the key.
One could then improve this by keeping a tree and a hash table. At any rate, there's still a hit on operations that add or remove elements, because they change two data structures now. And that doesn't even count modifying elements.
So, why not just sort the elements of the map?
tm.toSeq.sorted(Ordering by ((_: (String, Double))._2))
If your dataset is more complicated than strict key-value pairs:
There's a java dataset library that you can use to sort a dataset by any field represented in that dataset. Its easy-to-use and extremely flexible.
http://casperdatasets.googlecode.com
精彩评论