0
\$\begingroup\$

I have a list of Parcel objects and am trying to write a closure that picks the parcel object with highest count:

class Parcel { 
int id, 
int count,
String sender,
String recipient 
Parcel(int _id, int _count) {
 id = _id
 count = _count 
 } 
}
def parcels = [new parcel(1,5), new parcel(2,1), new parcel(3,3), new parcel(4,2), new parcel(5,4) ]

I have tried the below code which works fine:

parcels.sort{it.count}
parcels.reverse().first()

Is there a better way to pick the parcel with the highest count?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 10, 2014 at 19:17
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You could obviously try parcels.max{it.count}.

max and other useful operations on Groovy Collections are explained in the following article: https://groovy.codeplex.com/wikipage?title=Collections

answered Dec 11, 2014 at 2:34
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.