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!
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.
Sign up to join this communityHow 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) {
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.
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
sess.find(valuetobefound)
than
sess.find{it==valuetobefound}
v.findAll { it == v.max() }
\$\endgroup\$ – Arturo Herrero Feb 24 '12 at 17:41