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

Name: <Name>.
IdNumber: <Number>.
Age: <Number>.
Colors: <Color1, Color2, ..., ColorN>.

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?


2 Answers 2


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

  • \$\begingroup\$ Thank you. what can you say about the creating of colorsString? Is there another and better way? \$\endgroup\$
    – vesii
    Apr 27, 2019 at 15:42
  • \$\begingroup\$ The second link/ bottom half of the answer is answering that: the stream/sort you are doing is perfectly fine. My only recommendations would be, since you stated you didn’t like how it sorted out of the box, the second link contains several examples of how to change the sort by writing your own sorting algorithm :) \$\endgroup\$
    – DapperDan
    Apr 27, 2019 at 15:43
  • You can use the line separator property instead of "\n".
  • You can use a StringBuffer for more speed.
  • For better readability you can only pass the parameters. If you format them like I have done in the example below, you can just add a new parameter by copying/pasting an existing one. That's the reason I added the empty string "", so no need for deleting the comma after the last parameter.
  • I intentionally left the id unassigned to test the null.
  • To keep the example compact, I used an inner class StringUtilities(). Of course you should extract it and put it in a common place to access it from everywhere.

Here is the code:

public class Main {
    public static class StringUtilities {
       public static String newLine = System.getProperty("line.separator");

       public static String buildString(final Object... parameters) {
            StringBuffer buffer = new StringBuffer(20 * parameters.length);
            for (int i = 0; i < parameters.length; i++) {
                Object parameter = parameters[i];
                buffer.append(parameter == null ? "null" : parameter);
                if (i % 2 == 1) {
            return buffer.toString();

    private String name = "myName";
    private int age = 13;
    private String colors = "red, green";
    static class IdNumber {
    private IdNumber id;

    public String toString() {
        return StringUtilities.buildString(
            "name: ", name,
            "id: ", id,
            "age: ", age,
            "colors: ", colors,

    public static void main(String[] args) {
        System.out.println(new Main().toString());

Here is the console output:

name: myName
id: null
age: 13
colors: red, green

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.