Groovy / Grails:如何使用单独列表中给出的顺序对地图进行排序

时间:2015-02-05 22:44:17

标签: sorting groovy

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

  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"]或无。我怎样才能编写sort方法,以便在闭包中获取动态参数?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

一种方法是迭代排序顺序并使用findResult来获得“ufo”结果。关于这一点的丑陋部分是findResults不使用常规真理而sort需要一个int,因此需要一些elvis动作。 e.g。

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']