Is there any simpler way to find all elements in a list that are equal to the max element.

List v = [ 1,2,3,4,5,5  ]
def max = v.max()
def maxs = v.findAll { it == max }


  • 2
    \$\begingroup\$ Use an inline method: v.findAll { it == v.max() } \$\endgroup\$ – Arturo Herrero Feb 24 '12 at 17:41
  • \$\begingroup\$ @ArturoHerrero would that execute the max() method for each element in the list? or the compiler would optimize that to find the max only once and then compare to each element? \$\endgroup\$ – jambriz Jun 10 '20 at 13:45

How you've done it for the simple example is exactly how I would do it. I may use groupBy if I was dealing with a more complex object.

    List v = [ 1,2,3,4,5,5 ]
    def max = v.max()
    def results = v.groupBy {it}.get(max)
    assert [5,5] == results

In your code you go two times over your list (one time for the method List.max and one time for the method List.findAll). Of course this is acceptable, if you just have a small list. If your list is very large, you should go through it just one time.

When your list just contains primitives, it is enough to store the maximum and the count of this maximum in one variable, to go through the list and update both variables:

    def list = [1,2,3,4,5,5]
    def max = null
    def count = 0

    for (int i: list) {
        if (max == null || i > max) {
            max = i
            count = 1
        } else if (i == max) {

    println max // 5
    println count // 2

Of course the above code has more lines than yours, but should be faster for very large lists.


I think this way is the most convenient one:

def v = [ 1,2,3,4,5,5 ]
v = v.groupBy { it }.sort { 0 - it.key }.values()
assert [[5,5], [4], [3], [2], [1]] == v

It is a shame that Groovy makes it diffuclt for me to find or check element from a list of integers instead of using




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.