如何根据某些标准对groovy列表值进行排序

sri*_*ini -1 grails groovy

我有一个方案来排序基于值的域类属性.此属性可以接受格式为XXX-1的所有数字和字母数字值.

 def res= Book.listOrderByName()
Run Code Online (Sandbox Code Playgroud)

要么

 def res = Book.findAll("from Book order by name")
Run Code Online (Sandbox Code Playgroud)

给出相同的结果和结果是显示后面的字母数字值的第一个数字.我的问题是:这些值在 - 之前排序.例如,我有AB-1,AB-2,...... AB-12.

结果显示为AB-1,AB-10.AB-11,AB-2,AB-3,... AB-9

我的结果如下:

  [18001,18002,2,300,3901,42,9,AB-1,AB-10,AB-2,AB-21,AB-9]
Run Code Online (Sandbox Code Playgroud)

它应该显示值为:

  [2,9,42,300,3901,18001,18002,AB-1,AB-2,AB-9,AB-10,AB-21]
Run Code Online (Sandbox Code Playgroud)

Dón*_*nal 7

Groovy控制台中运行:

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']
Run Code Online (Sandbox Code Playgroud)