Making toString function more readable In Java I'm trying to make my code more readable. I created a function toString - It returns a string in the following format:

Name: &lt;Name&gt;.
IdNumber: &lt;Number&gt;.
Age: &lt;Number&gt;.
Colors: &lt;Color1, Color2, ..., ColorN&gt;.


Please notice that the colors should be sorted alphabetically. The function I wrote for now:

public String toString() {
    String colorsString = this.colors.stream().sorted().collect(Collectors.joining(", "));
    return "Name: " + this.Name+".\n" +
            "IdNumber: "  + this.Id+".\n" +
            "Age: " + this.Age+".\n" +
            "Colors: " + colorsString + ".";
}


I don't like the way I sorted the colors. I would like to use stream, but in other way if possible. Also, I feel like the format should be constant. Is it possible to keep it as a constant and add values to it? Future more I don't like the use of \n - is it possible without it?
This answer to a question on multi line strings contains a lot of good examples of trouble with building multi line string output this way but in particular I think the String.format approach works best with a template string.

Your setup would be something like

String template = “ Name: %s %n ID: ...”


And you would place it with

String formatted = String.format(template, nameString, idString,...);




Don’t like their sorting algorithm? I’d recommend extending your own! You can provide your own comparator for the sort stream function. This gives you complete control over how it sorts, at the expense of providing the desired sorting logic.
This article contains several examples of ways to extend your own comparators to this function