How can I sort List [Int] objects?

I want to sort List objects in Scala, rather than sorting items in a list. For example, if I have two Ints lists:

val l1 = List(1, 2, 3, 7) val l2 = List(1, 2, 3, 4, 10) 

I want to be able to put them in order, where l1> l2.

I created a case class that does what I need, but the problem is that when I use it, none of my other methods work. Do I need to implement all other methods in the class, for example, flatten, sortWith, etc.?

My class code looks like this:

 class ItemSet(itemSet: List[Int]) extends Ordered[ItemSet] { val iSet: List[Int] = itemSet def compare(that: ItemSet) = { val thisSize = this.iSet.size val thatSize = that.iSet.size val hint = List(thisSize, thatSize).min var result = 0 var loop = 0 val ths = this.iSet.toArray val tht = that.iSet.toArray while (loop < hint && result == 0) { result = ths(loop).compare(tht(loop)) loop += 1 } if (loop == hint && result == 0 && thisSize != thatSize) { thisSize.compare(thatSize) } else result } } 

Now, if I create an ItemSets Array, I can sort it:

 val is1 = new ItemSet(List(1, 2, 5, 8)) val is2 = new ItemSet(List(1, 2, 5, 6)) val is3 = new ItemSet(List(1, 2, 3, 7, 10)) Array(is1, is2, is3).sorted.foreach(i => println(i.iSet)) scala> List(1, 2, 3, 7, 10) List(1, 2, 5, 6) List(1, 2, 5, 8) 

Two methods that cause me problems:

 def itemFrequencies(transDB: Array[ItemSet]): Map[Int, Int] = transDB.flatten.groupBy(x => x).mapValues(_.size) 

I get an error:

An expression of type Map [Nothing, Int] does not match the expected type of Map [Int, Int]

And for this:

 def sortListAscFreq(transDB: Array[ItemSet], itemFreq: Map[Int, Int]): Array[List[Int]] = { for (l <- transDB) yield l.sortWith(itemFreq(_) < itemFreq(_)) } 

I got:

Cannot resolve sortWith character.

Is there a way that I can simply extend List [Int] so that I can sort the collection of lists without losing the functionality of other methods?

+8
sorting scala order
source share
1 answer

The standard library provides lexicographic ordering for collections of ordered things. You can put it in the scope, and you're done:

 scala> import scala.math.Ordering.Implicits._ import scala.math.Ordering.Implicits._ scala> val is1 = List(1, 2, 5, 8) is1: List[Int] = List(1, 2, 5, 8) scala> val is2 = List(1, 2, 5, 6) is2: List[Int] = List(1, 2, 5, 6) scala> val is3 = List(1, 2, 3, 7, 10) is3: List[Int] = List(1, 2, 3, 7, 10) scala> Array(is1, is2, is3).sorted foreach println List(1, 2, 3, 7, 10) List(1, 2, 5, 6) List(1, 2, 5, 8) 

An Ordering class of type is often more convenient than Ordered in Scala -it allows you to specify how to order some existing type without having to change your code or create a proxy class that extends Ordered[Whatever] , which, as you saw, can be very messy.

+15
source share

All Articles