我试图用Collator对地图进行排序,显然它只适用于列表
我正在使用这个:
import java.text.*
Collator collator = Collator.getInstance()
collator.setStrength(Collator.PRIMARY)
def list = [
[name:"áaa", title:"foo1"],
[name:"zzz", title:"foo2"],
[name:"éee", title:"foo3"],
[name:"ába", title:"foo4"],
[name:"aaa", title:"foo5"]
]
Collections.sort(list.name, collator);
list.collect{it.name}
返回[áaa, zzz, éee, ába, aaa]
但它应该返回:[áaa, aaa,ába,éee, zzz]
我该如何解决?我需要保留原始地图。 也许我可以使用其他类而不是Collator
谢谢!
答案 0 :(得分:1)
Collections.sort
修改您正在创建的列表list.name
,而不是之前存储的列表。它确实被排序,但结果在之后丢失:
更新:添加排序而不会丢失地图结构。
import java.text.*
def collator = Collator.instance
collator.strength = Collator.PRIMARY
def list = [
[name:"áaa"],
[name:"zzz"],
[name:"éee"],
[name:"ába"],
[name:"aaa"]
]
listc = list*.name
Collections.sort(listc, collator)
assert listc == ['áaa', 'aaa', 'ába', 'éee', 'zzz']
// Sorting without losing the map structure.
sortedList = list.sort(false) { a, b -> collator.compare a.name, b.name }
assert sortedList == [
[name:"áaa"],
[name:"aaa"],
[name:"ába"],
[name:"éee"],
[name:"zzz"],
]