Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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 }

Thanks!

share|improve this question
Use an inline method: v.findAll { it == v.max() } – Arturo Herrero Feb 24 '12 at 17:41

migrated from stackoverflow.com Feb 23 '12 at 19:06

3 Answers

up vote 2 down vote accepted

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
share|improve this answer

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) {
            count++
        }
    }

    println max // 5
    println count // 2

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

share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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