Klue
Klue

Reputation: 1357

How to order ListBuffer according to another ListBuffer

I have two ListBuffer objects:

val o1 = new ListBuffer[String]
val o2 = new ListBuffer[Double]

Both are of the same length. I want to sort o1 according to o2 values in descending order. This is how I try to tackle it:

// order `o2`
val ordered = o2.sorted(Ordering[Double].reverse)
// get indices
val ind = ordered.indices
// reorganize `o1` according to `ind`

First of all I don't know how to efficiently reorganize o1 according to ind. Secondly I wonder if a better approach exists (maybe using map, flatMap...). Maybe it makes sense to maintain a single data structure instead of having two ListBuffer's.?

Upvotes: 1

Views: 315

Answers (2)

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

If you want to know how things moved you need to track the indicies:

val o3 = o2.zipWithIndex.sortBy(_._1)

then you can get the elements of o1 in that order:

o3.map(e=>o1(e._2))  //> res0: ListBuffer(a, c, b)

but if you're going to do that, you might as well skip a step and incorporate the elements of o1 before you sort:

(o2 zip o1).sortBy(_._1).map(_._2)  //> res1: ListBuffer(a, c, b)

but if the elements of o1 and o2 are always in lock-step, then yes, maintaining a single data structure makes sense to me

Upvotes: 4

Dima
Dima

Reputation: 40500

Something like this prehaps:

 (o1 zip o2 sortBy(-_._2) unzip)._1

Upvotes: 2

Related Questions