3

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.

2 Answers 2

9

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))
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.