其他答案显示如何将字符串流收集到单个字符串中,以及如何从IntStream
. 这个答案显示了如何在字符流上使用自定义收集器。
如果要将整数流收集到字符串中,我认为最干净和最通用的解决方案是创建一个返回收集器的静态实用程序方法。然后,您可以Stream.collect
像往常一样使用该方法。
该实用程序可以像这样实现和使用:
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);
}
标准库中没有这样的东西有点令人惊讶。
这种方法的一个缺点是它需要将字符装箱,因为该IntStream
接口不适用于收集器。
一个未解决的难题是实用程序方法应该命名。收集器实用程序方法的约定是调用它们toXXX
,但toString
已经采用。