I am new to groovy Lists, and I have list as shown below:
Class File{
String name
int type
int revision
}
def fileList = [File1, File2, File3,....]
I want the fileList
to have the latest files
How do I do this in Groovy?
You can use Collection#groupBy
to create a map with an entry for each unique file name. You can then use Map#collect
to iterate over the contents of this map and create the list you want. The map's values will be a list of instances of File
, so Collection#max
will let you search for the one with the highest revision number.
class File {
String name
int type
int revision
String toString() { "File(name: $name; type: $type; revision: $revision)" }
}
final files = [
new File(name: 'foo', type: 0, revision: 0),
new File(name: 'bar', type: 0, revision: 0),
new File(name: 'bar', type: 0, revision: 1),
new File(name: 'baz', type: 0, revision: 0),
new File(name: 'baz', type: 0, revision: 1),
new File(name: 'baz', type: 1, revision: 1),
]
final result = files.groupBy { it.name }
. collect { name, revisions -> revisions.max { it.revision } }
I'm not sure what you meant when you said that the list should not have items of the same type. You'll notice that if there are two instances of File
with the same name and revision number but different types, this solution picks one arbitrarily.