2011-06-07 27 views
0

我知道我可以利用Groovy中的sort()函數對List進行排序。例如,我可以這樣做:如何在給定數字中對每個數字進行排序?

def numbers = [1,4,3] as List 
print numbers.sort() // outputs : [1,3,4] 

現在我想知道是否有在Groovy的功能,這確實是這樣的:如果我錯了

def number = 143 
// any method there to apply on number, so that i can get 134 as output!? 
// that is i get sorted my number? 

指正!

回答

3

這應該工作:

def number = 143 
def sorted = "$number".collect { it as int }.sort().join() as int 

即:

  1. "$number"
  2. collect s各自字符的數字轉換爲字符串爲int(所以你得到一個int列表)
  3. 來電sort()此陣列
  4. 來電join()所有整數回粘在一起作爲一個String
  5. 然後調用as int這個字符串一邊轉換回一個int

作爲一個,你不需要做:

def numbers = [1,4,3] as List 

在你的示例代碼... [1,4,3]List了,所以as List是多餘的

+0

@tim,看起來不錯,但在控制檯不起作用 - 獲取INT上線不匹配的構造函數():DEF分類=「$號」 .collect {it as int} .sort()。join()as int – virtualeyes 2011-06-07 11:18:10

+1

在我的控制檯中工作。收集閉包中的「as int」可以忽略,因爲排序也適用於字符串表示的數字。 – 2011-06-07 11:37:28

+0

@virtual Odd ...它在Web控制檯和1.8 – 2011-06-07 11:38:36

1

編輯

這是更好的(@tim有答案,所以不要改變請,只是工作在我的Groovy的印章;-))

從高到低的順序版本是:

def n = 143 
println "$n".collect{it}.sort().reverse().join().toInteger() // or "as int" as you like 

編輯 這是一個好一點:

def n = 143 as String 
println n.collect{it}.sort().join().toInteger() 

原始 黑客攻擊,但工程:

def n = 143.collect{it}.join(',').toList().sort().join() 
+0

感謝您的回答:) – 2011-06-07 15:35:14

相關問題