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.
You can use String.CASE_INSENSITIVE_ORDER
to order strings in case-insensitive way.
If you also at the same time want to farther specify order of elements which current comparator considers as equal (like String.CASE_INSENSITIVE_ORDER
would do for "Regen"
and "regen"
) then you can use Comparator#thenComparing
method and pass to it Comparator which would sort those equal elements like you want.
"Regen", "regen"
as "regen", "Regen"
(lower-case before upper-case) you can simply reverse their natural order with Comparator.reverseOrder()
.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)