Ray
Ray

Reputation: 6095

groovy sort list using part of list element

I've got a list that looks like this:

C:\basedir\2011_April\data_20110407.csv
...
C:\basedir\2011_January\data_20110101.csv

The second file comes later in the list, because "January" is after "April". I need this list to instead be sorted by the file date, i.e. the data_20110101.csv file should come before the data_20110407.csv file (keeping the whole directory path). Can someone give me an example that can sort on subfields like this?

Upvotes: 1

Views: 1387

Answers (1)

Christoph Metzendorf
Christoph Metzendorf

Reputation: 8078

You can use the sort method on the list and pass a closure that extracts the date from each string as the sort criteria:

fileList.sort { 
  def matcher = it =~ /(\d{8})\.csv/
  matcher[0][1] 
}

Upvotes: 4

Related Questions