Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sort string both alphabetically and keep ASCII order

The list is: Arrays.asList("Za", "ab", "AB", "Sa", "1ab", "Ab", "!Ab");

If I use stream().sorted() then the order is: !Ab 1ab AB Ab Za ab --> Za should not be in front of ab.

If I use sorted(String.CASE_INSENSITIVE_ORDER) then the order is !Ab 1ab ab AB Ab Za --> This time, AB is behind ab.

Is there any way to combine the two rules so we have list sorted alphabetically and uppercase is greater than lower case?


Added Example: 1AB - A0B - AbD - aBD - abd1 - ZAB Sorted alphabetically (Z is never in front of a) and Number > Uppercase > Lowercase (AbD > aBD)

like image 906
D.T Avatar asked Sep 11 '26 02:09

D.T


1 Answers

The problem is that ab and AB are equal; hence themselves are unordered in the result. So add a normal comparison, as capitals come before small letters.

list.stream()
    .sorted(String.CASE_INSENSITIVE_ORDER
            .thenComparing(Comparator.naturalOrder()))

After comment

list.stream()
    .sorted(String.CASE_INSENSITIVE_ORDER
            .thenComparing(Comparator.reverseOrder()))
like image 191
Joop Eggen Avatar answered Sep 12 '26 16:09

Joop Eggen