Following up this question I wonder why maxBy of Traversable[T] returns a single value T instead of a sequence of T (list or similar). It looks like a pretty common case. For example (from the previous question):
For the list of students with their grades
List(Student("Mike", "A"), Student("Pete", "B"), Student("Paul", A))"
I want to get
List(Student("Mike", "A"), Student("Paul", A))
Does anybody know about any standard implementation of maxBy, which returns a sequence of found items?
There is no single command. The shortest I know of–which will group everything not just the maximum value as an intermediate–is
For greater efficiency, folds are good general-purpose tools for finding sums and maxima and various similar things. Basically, any time you need to run over your collection while accumulating some answer, use a fold. In this case,
will perform
maxBy(f)if you don’t mind re-evaluating the function twice for each element, whilewill do it with only one evaluation per element. If you want to keep a sequence, you can modify this to
to keep the list (the corresponding single-evaluation form is left as an exercise to the reader).
Finally, even the near-maximum efficiency version isn’t all that hard to manage, if you’re willing to use a few mutable variables (hopefully well-hidden in a code block like I have here)
(this will return in reverse order, incidentally).