Search code examples
javalistsortingcollator

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

Solution

  • 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]