Search code examples
javasortingalphabetical

Printing a list in alphabetical order with letter headings


I have a list of strings in alphabetical order I want to print, but I want to do so with corresponding letter headings. For example:

["Blue","Cat in hat","Zebra","2 Words"]

## B
    Blue
## C
    Cat in hat
## Z
   Zebra
## [0-9]
   2 Words

Whats the best way to do this? It should be case insensitive, so "hello" and "Hello" both go under H.


Solution

  • This would help you:

    Note: Assuming the list is sorted.Otherwise you need to do sort first.

    for (String str : stringList) {
    
        if (Character.isDigit(str.charAt(0))) {
            if (!Character.isDigit(previousChar)) {
            System.out.println("## [0-9]");
            }
        } else if (Character.toUpperCase(str.charAt(0)) != previousChar) {
    
            System.out.println("## " + Character.toUpperCase(str.charAt(0)));
        }
    
        previousChar = Character.toUpperCase(str.charAt(0));
    
        System.out.println(str);
    }