Reputation: 385
below is the list of files :
abc_2019_01_30_5816789.bak, abc_2019_01_31_2992794.bak,
xyz_2019_01_26_4690992.bak, xyz_2019_01_27_8319704.bak,
pqr_2019_01_30_5986789.bak, pqr_2019_01_31_3142809.bak,
test_2019_01_30_6076789.bak, test_2019_01_31_3232818.bak,
testing_2019_01_30_6026789.bak, testing_2019_01_31_3192814.bak,
repair_2019_01_30_6116789.bak, repair_2019_01_31_3282823.bak,
factory_2019_01_30_5646789.bak, factory_2019_01_31_2802775.bak
i have this list in "parsedlist", so when i sort them and pick the latest 7, i see a couple of duplicate files. my requirement is to have 7 unique files which are latest and write them to a text file. I have tried the below code :
List<String> sortedList = parsedList.sort(false).reverse()
println sortedList.take(7)
String filename = "D:\\latest.txt"
new File(filename).write(sortedList.take(7).join(","))
Upvotes: 0
Views: 383
Reputation: 171084
An alternative for fun (as there are many ways to do things in Groovy)
println parsedList.groupBy { it.split(/_\d{4}_/).head() }
.collect { k, v -> v.sort().last() }
Upvotes: 1
Reputation: 1559
You are just sorting the list by the full filename, which gives you all the "xyz" files first, then "testing" and so on...
One way would be to use groupBy
to first group the files by prefix, then sort each group and finally pick the last item from each group.
println parsedList
.groupBy{it[0..-24]} // group by prefix (remove timestamp), results in a map like [abc:['abc_2019_...', 'abc_2019_...'], xyz:[...], ...]
.values() // collect the values from the KeyValuePairs (i.e. just the lists with the strings) --> [['abc_2019_...', 'abc_...'], ['xyz_...','xyz_...'], ...]
*.sort() // sort each of the lists
*.getAt(-1) // from each list take the last item
Upvotes: 2