0

(我使用Java)

我想使用 Collat​​or 按属性对对象子列表进行排序,以便按字母顺序排序但忽略重音符号。问题是我尝试了不同的东西,但没有奏效。

这会对子列表进行排序,但不会忽略重音符号:

newList.subList(0, 5).sort(Comparator.comparing(element -> element.getValue()));

这是我要使用的整理器:

Collator spCollator = Collator.getInstance(new Locale("es", "ES"));

我希望输出是一个按字母顺序排序的子列表,您可以使用 .getValue() 忽略重音符号访问该属性。

4

2 回答 2

3

Collat​​or 也是 Comparator。如果元素是字符串:

List<String> list = Arrays.asList("abc", "xyz", "bde");
Collator spCollator = Collator.getInstance(new Locale("es", "ES"));
list.sort(spCollator);

如果元素是自定义对象:

List<Element> list = Arrays.asList(new Element("abc"), new Element("xyz"), new Element("bde"), new Element("rew"), new Element("aER"),
           new Element("Tre"), new Element("ade"));
   list.subList(0, 4).sort(new MyElementComparator());
   System.out.println(list);

private static class MyElementComparator implements Comparator<Element>{
   Collator spCollator = Collator.getInstance(new Locale("es", "ES"));
   public int compare (Element e1, Element e2){
       return spCollator.compare(e1.getValue(), e2.getValue());
   }
}

或 lambda 方式:

List<Element> list = Arrays.asList(new Element("abc"), new Element("xyz"), new Element("bde"), new Element("rew"), new Element("aER"),
        new Element("Tre"), new Element("ade"));
Collator spCollator = Collator.getInstance(new Locale("es", "ES"));
list.subList(0, 4).sort((e1, e2)-> spCollator.compare(e1.getValue(), e2.getValue()));
System.out.println(list);
于 2019-07-25T10:42:34.303 回答
0

而不是使用Comparator.comparing,您创建一个 lambda 以首先提取值,然后使用整理器进行比较。

Collator spCollator = Collator.getInstance(new Locale("es", "ES"));
newList.subList(0, 5).sort((e1, e2) -> spCollator.compare(e1.getValue(), e2.getValue()));
于 2019-07-25T10:52:31.093 回答