javasortingarraylistalphabetical-sort

Does Java have an alphabetical order like this?


Like in this example, https://www.duden.de/rechtschreibung/Regen_Niederschlag , the words are sorted in the following way: "regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..." that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".

ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
        "regen", "Regen", "Regenabflussrohr",
        "Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
        regen.add(x);
}

Collections.sort(regen) response:

[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,
regelwidrig, regen, regenarm]// lowercase at the end

I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as: Collections.SomeMethod(regen); or Collections.Sort(regen, some_extra_parameter); But I haven't found after deep google search, unfortunately.


Solution

  • So your code can look like:

    regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
    

    Demo:

    ArrayList<String> regen = new ArrayList<String>(
            Arrays.asList("regelwidrig", "Regelwidrigkeit", "Regelzeit",
                "Regen", "regen", "Regenabflussrohr",
                "Regenanlage", "regenarm", "Regenbö", "Regenbogen")
    );
    
    regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
    System.out.println(regen);
    
    

    Result: [regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö]

    (notice "Regen", "regen" ware swapped)