jeb2
jeb2

Reputation: 189

maxBy() multiple attributes of objects in List()

Say I have a list of books

val books = List(Book)

where Book(bookID: String, bookName: String) and a map

val scores = Map(bookID -> score:float)

I would like to get the book with the highest score first, then alphabetically by bookName

Getting the book with the highest rated score is rather simple:

val bestBook = books.maxBy(x => score(x.bookID))

But in case of multiple books with the same score I would then like to sort by the bookName. I'm not sure how to add a second criterion to maxBy? I suppose I can maxBy() score first, then I retrieve the score of bestBook, and filter books with the max score, then minBy() the bookName?

But that seems really cumbersome, is there a more efficient way of doing this? I've seen previous threads that does something similar with the Ordering implicit: Scala Ordering by multiple values, but I couldn't figure out how to define Ordering in this context.

Upvotes: 1

Views: 478

Answers (1)

Gaël J
Gaël J

Reputation: 15105

Using maxBy by both the higher score (thanks to the - on the score) and the name:

books
  .maxBy(b => (-score(b.bookId), b.name))

The same ordering on tuple can be used for sorting if needed.

Upvotes: 3

Related Questions