简体   繁体   中英

Collator Locale German - How to sort accented letters only after the normal ones

i have used Collator to sort an array of objects. But I found out that it treats accented letters like normal ones:

Aktivierung
Änderung
Auszahlung
Bar

instead i would like to have this

Aktivierung
Auszahlung
Änderung
Bar

the accented letter should be placed right after the normal ones. That is also for o/ö and u/ü.

Collator collator = Collator.getInstance(Locale.GERMAN);
...
private void sortDocumentiByCategoria(final Collator collator, List<ListDocumenti> listDocumenti) {
      Collections.sort(listDocumenti, new Comparator<ListDocumenti>(){
          @Override
          public int compare(ListDocumenti arg0, ListDocumenti arg1) {
              return collator.compare(arg0.getDescrizione(), arg1.getDescrizione());
          }
      });
}

You are complicating the sorting more than nyou need...

Collections.sort will bring the umlauts to the end

 List<String> l = Arrays.asList("Aktivierung", "Änderung", "Auszahlung", "Bar");
 System.out.println(l);
 Collections.sort(l);
 System.out.println(l);

[Aktivierung, Änderung, Auszahlung, Bar]

[Aktivierung, Auszahlung, Bar, Änderung]

'Edit:

implement a collator based on your own defined german Rules...

 List<String> l = Arrays.asList("Aktivierung", "Änderung", "Auszahlung", "Bar");
 String germanRules = "< A < a < Ä < ä < O < o < Ö < ö < U < u < Ü < ü";

 RuleBasedCollator ruleBasedCollator = new RuleBasedCollator(germanRules);
 Collections.sort(l, ruleBasedCollator);
 System.out.println(l);

output will be:

Aktivierung, Auszahlung, Änderung, Bar

It took awhile, but I figured it out. Here you go!

public static void main(String[] args) throws IOException {
    List<String> list = Arrays.asList("Änderung", "Aktivierung", "Auszahlung", "Bar");

    Collections.sort(list, createCollator());

    System.out.println(list);
}

private static RuleBasedCollator createCollator() {
    String german = "" +
                    "= '-',''' " +
                    "< A< a< ä< Ä< B,b< C,c< D,d< E,e< F,f< G,g< H,h< I,i< J,j" +
                    "< K,k< L,l< M,m< N,n< O< o< Ö< ö< P,p< Q,q< R,r< S,s< T,t" +
                    "< U< u< Ü< ü< V,v< W,w< X,x< Y,y< Z,z" +
                    "& ss=ß";

    try {
        return new RuleBasedCollator(german);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

Testing it yields the following:

>> [Aktivierung, Auszahlung, Änderung, Bar]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM