java – The simplest way to print an `IntStream` as a` String`

Other answers show how to collect a stream of strings into a single string and how to collect characters from a IntStream. This answer shows how to use a custom binder on a character stream.

If you want to collect a stream of integers into a string, I think the cleanest and most general solution is to create a static utility method that returns a collector. Then you can use the method Stream.collect as usual.

This utility can be implemented and used like this:

public static void main(String[] args){
    String s = "abcacb".codePoints()
        .filter(ch -> ch != 'b')
        .boxed()
        .collect(charsToString());

    System.out.println("s: " + s); // Prints "s: acac"
}

public static Collector<Integer, ?, String> charsToString() {
    return Collector.of(
        StringBuilder::new,
        StringBuilder::appendCodePoint,
        StringBuilder::append,
        StringBuilder::toString);
}

It is a little surprising that there is no such thing in the standard library.

A disadvantage of this approach is that it requires characters to be boxed since the interface IntStream it does not work with collectors.

An unsolved and difficult problem is what should be called the utility method. The convention for collector utility methods is to call them toXXXbut toString is already in use.

Leave a comment