【问题标题】:How can I sort by property using a collator ? (Java)如何使用整理器按属性排序? (爪哇)
【发布时间】:2019-07-25 10:33:41
【问题描述】:

(我使用Java)

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

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

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

这是我要使用的整理器:

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

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

【问题讨论】:

  • 使用spCollator.compare()
  • 还将整理者的分解设置为 CANONICAL,将强度设置为 PRIMARY

标签: java sorting collator


【解决方案1】:

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);

【讨论】:

  • 这将无法按属性排序。您使用的是字符串列表,我使用的是对象列表。
  • list.sort(Comparator.comparing(Element::getValue, spCollator)); 假设对象的类是 Element。
【解决方案2】:

您不是使用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-05-10
    • 2012-11-11
    • 2016-09-03
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 2011-05-23
    • 2020-08-28
    • 1970-01-01
    相关资源
    最近更新 更多