Reputation: 73
I have an array of pairs:
Array(("hello",200.00),("name",100.00),("a",200.00),("say",150.67))
I want it sorted as:
Array(("a",200.00),("hello",200.00),("say",150.67),("name",100.00))
Sorted in descending by value first, then ascending by key
Upvotes: 1
Views: 1702
Reputation: 7348
You can group by Value -> Sort it -> map each of the grouped to sorted by key Seq -> reverse all Seq
val groupdByValue = a.groupBy { case (k, v) => v }.toSeq
val groupsSortedByValue = groupdByValue.sortBy { case (value, group) => value }
val sortedByValueThenKey = groupsSortedByValue.flatMap { case (k, v) => v.sortBy { case (k, v) => v } }.reverse
sortedByValueThenKey: Seq[(String, Double)] = ArrayBuffer((a,200.0), (hello,200.0), (say,150.67), (name,100.0))
Upvotes: 0
Reputation: 183
Try using sortWith:
val a = Array(("hello",200.00),("name",100.00),("a",200.00),("say",150.67))
val sorted = a.sortWith((a, b) => a._2 > b._2 || (a._2 == b._2 && a._1 < b._1))
Upvotes: 2