2016-07-06 37 views
2

文本+日期字符串列表進行排序我有一個字符串列表,每一個都包含日期的文字是這樣的:如何在Groovy

"foo_6.7.2016" 
"foo_5.10.2016" 
"foo_6.30.2016" 
"foo_6.23.2016" 
"foo_6.2.2016" 
"foo_5.22.2016" 

我需要時間對它們進行排序,並得到這個:

"foo_6.30.2016" 
"foo_6.23.2016" 
"foo_6.7.2016" 
"foo_6.2.2016" 
"foo_5.22.2016" 
"foo_5.10.2016" 

回答

5

另一種可能是:

def foos = [ 
    "foo_6.7.2016", 
    "foo_5.10.2016", 
    "foo_6.30.2016", 
    "foo_6.23.2016", 
    "foo_6.2.2016", 
    "foo_5.22.2016" 
] 

def sorted = foos.sort(false) { Date.parse('M.d.yyyy', it - 'foo_') }.reverse() 
+0

尼斯 - 絕對比我的方法更groovy的方式 –

+0

你的方式有好處,你只能解析日期一次 –

+0

如果使用太空船操作員... f(b)<=> f(a)然後reverse()可以消失?假設f是在這個答案中指定的閉包。 –

4

要儘快得到答案,需要大量的清理:

def dates = [ 
"foo_6.7.2016" 
"foo_5.10.2016" 
"foo_6.30.2016" 
"foo_6.23.2016" 
"foo_6.2.2016" 
"foo_5.22.2016" 
] 

def prefix = "foo_" 
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M.d.yyyy") 
def sorted_dates = dates.collect{ sdf.parse(
    it, new java.text.ParsePosition(prefix.length())) }.sort().reverse() 
def newDates = sorted_dates.collect{ "${prefix} + ${sdf.format(it)}"} 
println newDates 
+0

謝謝,這對我很有用! – fred05