使用带有Collat​​or的重音符号对字符串进行排序

时间:2014-09-18 19:00:29

标签: java collections groovy collation

我试图用Collat​​or对地图进行排序,显然它只适用于列表

我正在使用这个:

 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]

我该如何解决?我需要保留原始地图。 也许我可以使用其他类而不是Collat​​or

谢谢!

1 个答案:

答案 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"],
]