5
\$\begingroup\$

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!

\$\endgroup\$

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

This question came from our site for professional and enthusiast programmers.

  • 2
    \$\begingroup\$ Use an inline method: v.findAll { it == v.max() } \$\endgroup\$ – Arturo Herrero Feb 24 '12 at 17:41
4
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
-2
\$\begingroup\$

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

      sess.find(valuetobefound)

than

     sess.find{it==valuetobefound}
\$\endgroup\$

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.