HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Groovy: find all elements in a list equal to the max element

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theelementsallequalmaxelementfindlistgroovy

Problem

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!

Solution

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

Code Snippets

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

Context

StackExchange Code Review Q#9331, answer score: 4

Revisions (0)

No revisions yet.