How can I sort by property using a collator ? (Java)

我与影子孤独终老i 提交于 2021-01-29 11:23:23

问题


(I use Java)

I want to sort a sublist of objects by a property using a Collator so that is sorted by alphabetical order but ignoring accents. Problem is I have tried different things and none work.

This sorts the sublists but doesn't ignore accents:

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

This is the collator I want to use:

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

I expect the output to be a sublist sorted by alphabetical order by the property which you can access with .getValue() ignoring the accents.


回答1:


Collator is also a Comparator. If the elements are String:

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

If the elements are custom Object:

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

Or the lambda way:

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



回答2:


Instead of using Comparator.comparing, you create a lambda to first extract the value and then use the collator to compare.

Collator spCollator = Collator.getInstance(new Locale("es", "ES"));
newList.subList(0, 5).sort((e1, e2) -> spCollator.compare(e1.getValue(), e2.getValue()));


来源:https://stackoverflow.com/questions/57199918/how-can-i-sort-by-property-using-a-collator-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!