Search code examples
javaprintingseparator

Remove last separator from print statement


Here's a method for sorting an integer array. How can I remove the last separator form the output?

public void Sort(int[] sort) {
        for (int a:sort) {
            System.out.print(a+ ", ");
        }
    }

Output

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 

Desired Output

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

Solution

  • If you are using Java 8, a very clean solution is using the new StringJoiner class. This class was designed to join Strings together with a custom separator, and possibly with a prefix / suffix. With this class, you don't need to worry about deleting the last separator as you do in your snippet.

    public void sort(int[] sort) {
        StringJoiner sj = new StringJoiner(",");
        for (int a : sort) {
            sj.add(String.valueOf(a));
        }
        System.out.println(sj.toString());
    }
    

    You could also drop the for loop and use Streams instead:

    String str = Arrays.stream(sort).mapToObj(String::valueOf).collect(joining(","));