Java – Prioritize uppercase letters before lowercase letters in Java

Prioritize uppercase letters before lowercase letters in Java… here is a solution to the problem.

Prioritize uppercase letters before lowercase letters in Java

Hello, I’m creating a method that sorts the elements in an array alphabetically, but they are sorted based on ASCII. I need to sort them in such a way that uppercase words are displayed first and lowercase words are displayed. For example, if I have {Apple,Orange,Car,art,olive}, the sort should be Apple,art,Car,Orange,olive

public static ArrayList<String> sort(ArrayList<String> lines) {
        lines.sort(String::compareToIgnoreCase);
        return lines;
    }

Here is my code now, I know I have to remove compareToIgnoreCase but what should I do?

Solution

Use Comparator.comparing() to first compare the first letters of a word in a case-insensitive way, and then use the natural order of uppercase before lowercase in the next step.

List<String> list = Arrays.asList("Apple","Orange","Car","art","olive");
list.sort(Comparator.<String, Character>comparing(s -> Character.toUpperCase(s.charAt(0)))
                .thenComparing(s -> s));
System.out.println(list);  [Apple, art, Car, Orange, olive]

Related Problems and Solutions