Reputation: 149
I have to sort a collection of values depending on a set of keys I have available as sublists of another list. Currently, I have the following code which does the job properly. However, it uses a mutable collection and I know this is not the best way to do this in Scala. What would be the pretty "Scala way" of doing this ? Thanks.
var sorted: IndexedSeq[IndexedSeq[Any]]
//sortKeys is a list of lists containing sorting properties (index,descending/ascending)
for (i <- (0 until sortKeys).reverse) {
val index = sortKeys(i).get(i).getIndex
val desc = sortKeys.get(i).descending
if (desc) {
sorted = sorted.sorted { (t1: IndexedSeq, t2: IndexedSeq) => -t1(index).asInstanceOf[Comparable[Any]].compareTo(t2(index)) }
} else {
sorted = sorted.sorted { (t1: IndexedSeq, t2: IndexedSeq) => t1(index).asInstanceOf[Comparable[Any]].compareTo(t2(index)) }
}
}
Upvotes: 0
Views: 281
Reputation: 262494
Rough sketch:
val sortKeys = Seq( (1,true), (2, false))
val input = Seq( Array("a", "b", "c"), Array("a", "x", "c" )
sortKeys.foldRight(input){
case ( (index, ascending), acc) =>
acc.sortWith( (a,b) => if (ascending) a(index) > b(index)
else a(index) < b(index))
}
Upvotes: 2