Matt
Matt

Reputation: 73

Sort Scala, first by value and then by key

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

Answers (3)

Odomontois
Odomontois

Reputation: 16308

Simple as

array sortBy {case (k,v) => (-v,k)}

Upvotes: 5

Maxim
Maxim

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

James Tidman
James Tidman

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

Related Questions