Groovy/Grails:如何按照单独列表中给定的顺序对地图进行排序

Groovy/Grails : How to sort the map with order given in separate list

我有一个给定的数据列表:

  def given  = [
  [Country:'Japan',Flag:'Yes',Event:'New Year'],
  [Country:'china',Flag:'No',Event:'Spring Festival'],
  [Country:'uk',Flag:'No',Event:'National Holiday'],
  [Country:'us',Flag:'Yes',Event:'Labour Day'],
  [Country:'us',Flag:'Yes',Event:'New Year'],
  [Country:'uk',Flag:'Yes',Event:'Memorial Day']
]

我可以使用 groovy 排序方法进行排序:

given = given.collect().sort { a, b  ->
  a.Flag <=> b.Flag ?: a.Event <=> b.Event 
}

但是,如果用户提到排序依据并将其存储在单独的列表中,我该怎么办 例如:def sortOrder = ["Country","Flag"],这里的排序顺序是动态的,用户可以选择:["Country","Flag"] / ["Country","Flag","Event"] 或none。我如何编写排序方法以便它在闭包中使用我的动态参数?

一种方法是迭代排序顺序并使用 findResult 获得 "ufo" 结果。丑陋的部分是 findResults 不使用 groovy truth 而 sort 需要一个 int,所以需要一些 elvis 动作。例如

def given  = [[Country:'Japan',Flag:'Yes',Event:'New Year'],
    [Country:'china',Flag:'No',Event:'Spring Festival'],
    [Country:'uk',Flag:'No',Event:'National Holiday'],
    [Country:'us',Flag:'Yes',Event:'Labour Day'],
    [Country:'us',Flag:'Yes',Event:'New Year'],
    [Country:'uk',Flag:'Yes',Event:'Memorial Day']]

def sortorder = ['Flag', 'Event']

assert given.sort{ a,b -> 
    sortorder.findResult{ a[it] <=> b[it] ?: null }  ?: 0
}.first()==[Country:'uk', Flag:'No', Event:'National Holiday']

假设您在变量 order 中有自定义订单,尝试

given.sort { a, b ->
    order.inject(0) { o, e -> 
        o ?: a[e] <=> b[e]
    }
}