BAR
BAR

Reputation: 17121

Scala Ordering by multiple values

I am trying to use Ordering[T] with multiple types.

case class Person(name: String, age: Int)

Person("Alice", 20)
Person("Bob", 40)
Person("Charlie", 30)

object PersonOrdering extends Ordering[Person] {
  def compare(a:Person, b:Person) =
    a.age compare b.age
}

How do I sort by both name and age?

The collection needs to remain sorted with updates.

Upvotes: 3

Views: 2360

Answers (2)

Chris Martin
Chris Martin

Reputation: 30736

Order by the tuple of name and age.

Also, it's generally easier to call Ordering.by rather than extend Ordering yourself.

case class Person(name: String, age: Int)

implicit val personOrdering: Ordering[Person] =
  Ordering.by(p => (p.name, p.age))

Seq(Person("a", 2), Person("b", 1), Person("a", 1)).sorted
// Seq[Person] = List(Person(a,1), Person(a,2), Person(b,1))

Upvotes: 9

Omid
Omid

Reputation: 1989

You can make a tuple and sort that:

val people = List(
Person("Alice", 20),
Person("Bob", 40),
Person("Charlie", 30)
)

people.orderBy(x => (x.name,x.age))

In case of extending Ordering should be the same, make a tuple and compare them

Upvotes: 3

Related Questions