1

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.

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

ah I didn't think of that, but in terms of performance, isn't sortBy going to be O(nlog n) while maxBy is O(n) (i think?)
Right, you can use the same approach with maxBy on a tuple.
Don't recommend sort for a simple max operation.
Sure, edited the post :)

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.