Other answers show how to collect a stream of strings into a single string and how to collect characters from an IntStream
. This answer shows how to use a custom collector on a stream of characters.
If you want to collect a stream of ints 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 Stream.collect
method 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's a bit surprising that there isn't something like this in the standard library.
One disadvantage of this approach is that it requires the chars to be boxed since the IntStream
interface does not work with collectors.
An unsolved and hard problem is what the utility method should be named. The convention for collector utility methods is to call them toXXX
, but toString
is already taken.