开发者

How I can sort a each number in a given number?

I know i can make use of sort() function in Groovy to sort List. For examp开发者_开发知识库le I can do this :

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

Now i want to know whether there is a function in Groovy, which does something like this:

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?

Correct me if am wrong!


This should work:

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

That:

  1. Converts the number to a String "$number"
  2. collects each char as an int (so you get a List of int)
  3. calls sort() on this array
  4. calls join() to stick all the ints back together as a String
  5. then calls as int to convert this String back into an int

As an aside, you don't need to do:

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

in your example code... [1,4,3] is a List already, so as List is superfluous


Edit

And this is even better (@tim has the answer so don't change please, just working on my Groovy chops ;-))

a descending order version would be:

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

Edit This is a bit better:

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

Original Hacked, but works:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜