开发者

how to sort groovy list values based on some criteria

I have one scenario to sort the values based domain class property. This property may acept all numeric and alphanumeric values in the format XXX-1.

 def res= Book.listOrderByName()

or

 def res = Book.findAll("from Book order by name")

Giving the same result and result is displaying first numbers latter alphanumeric values. My problem is : these values are sorted before 开发者_Python百科-. for example i have AB-1,AB-2,...AB-12.

The result is displayed as AB-1,AB-10.AB-11,AB-2,AB-3,..AB-9

I have result like:

  [18001,18002,2,300,3901,42,9,AB-1,AB-10,AB-2,AB-21,AB-9]

It should display the value as:

  [2,9,42,300,3901,18001,18002,AB-1,AB-2,AB-9,AB-10,AB-21]


Run this in the Groovy console:

List sort(list) {

  list.sort {a, b ->
    a.class == b.class ? a <=> b : a instanceof Integer ? -1 : 1
  }
}

// Test the sort function
def list = [18001,18002,2,300,3901,42,9,'AB-1','AB-10','AB-2','AB-21','AB-9']
assert sort(list) == [2, 9, 42, 300, 3901, 18001, 18002, 'AB-1', 'AB-10', 'AB-2', 'AB-21', 'AB-9']
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜