-3

I want to make something looked like an dictionary, where there are a lot of words starting with different letters. How can I use Collections.sort() so that I can sort all the words and print the info about the letters that are next. The result should look like:

Words starting by A:
AAA
AAB
ABB
ABC
Words starting by B:
BAA
BAB
BBB
BBC

That's my code:

public Dictionary(){
    private ArrayList<String> words;

    @Override
    public String toString(){
        Collections.sort(words);
        String str = "";
        for(int i = 0; i< words.size() ; i++){
            str += words.get(i) + "\n";

        }
        return str;
    }
}
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56

1 Answers1

0

First of all I would recommend not using Collections.sort() on a filed in your toString() method. Beside that you should use a StringBuilder for your String generation. Read this for more detailed information.

Beside that you can use a new variable to check if the next word starts with a different character:

@Override
public String toString() {
    Collections.sort(words);
    StringBuilder result = new StringBuilder();
    String startCharacter = null;
    for (String word : words) {
        if (startCharacter == null || !word.startsWith(startCharacter)) {
            startCharacter = word.substring(0, 1);
            result.append("Words starting by ").append(startCharacter).append(":\n");
        }
        result.append(word).append("\n");
    }
    return result.toString();
}

Alternatively you can use the Java Stream API:

@Override
public String toString() {
    return words.stream()
            .sorted()
            .collect(Collectors.groupingBy(word -> word.substring(0, 1), LinkedHashMap::new, Collectors.joining("\n")))
            .entrySet().stream()
            .map(e -> "Words starting by " + e.getKey() + ": \n" + e.getValue())
            .collect(Collectors.joining("\n"));
}

The result in both cases will be:

Words starting by A: 
AAA
AAB
ABB
ABC
Words starting by B: 
BAA
BAB
BBB
BBC
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56