Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to sort list of objects

Tags:

scala

I have a list of objects of type A. In a first iteration I assign each object a double value 0 < x < 1 and then want to sort each object according to it's x value.

Currently I use a wrapper class that stores the object and it's x value to make a comparable list.

Is there a datatype provided by Scala that allows me something like:

 var result = new SortedList[Double, A]
 result.insert(x,a)
 result.insert(x1,a1)
 result.insert(x2,a2)

and then

  println(result.mkString)
like image 385
Chris Avatar asked Mar 17 '12 15:03

Chris


3 Answers

You can actually do this quite easily with normal Scala lists and their sortBy method. Here's a brief REPL session showing how:

scala> class A(val value: Double) { override def toString = "A:" + value }
defined class A

scala> List(new A(6), new A(1), new A(3)) sortBy (_.value)
res0: List[A] = List(A:1.0, A:3.0, A:6.0)
like image 51
Destin Avatar answered Oct 23 '22 07:10

Destin


Use tuples instead of creating a new wrapper class.

List((1.2, "a1"), (0.1, "a2"), (0.9, "a3")).sorted
// List((0.1,a2), (0.9,a3), (1.2,a1))
like image 39
Luigi Plinge Avatar answered Oct 23 '22 05:10

Luigi Plinge


I go like this. For getting top c words in a hashmap:

  def getTopCWordsDeclarative(input: mutable.HashMap[String, Int], c: Int): Map[String, Int] = {
    val sortedInput = input.toList.sortWith(_._2 > _._2)
    sortedInput.take(c).toMap
  }
like image 29
JasonG Avatar answered Oct 23 '22 07:10

JasonG