如何在Java 1.8的reduce方法内使用StringBuilder? [英] How to use StringBuilder inside the reduce method in java 1.8?
问题描述
String s = "apples for you";
StringBuilder returnString = new StringBuilder("");
Arrays.stream(s.split(" "))
.reduce(returnString, (acc, str) -> acc.append(str.charAt(0)));
每个单词的预期输出首字母,即 afy
.
Expected output first letter of each word, i.e. afy
.
但是在 acc.append
处出错, acc
被视为 String
.
But getting error at acc.append
, acc
is treated to be a String
.
推荐答案
您对 reduce
的使用不正确.您打算调用的重载是带有3个参数的重载,该重载还应为 StringBuilder
使用一个二进制运算符:
Your use of reduce
is incorrect. The overload you intend to call is the one with 3 parameters, which should also take a binary operator for StringBuilder
:
StringBuilder returnString = Arrays.stream(s.split(" "))
.reduce(new StringBuilder(""),
(acc, str) -> acc.append(str.charAt(0)),
(sb1, sb2) -> sb1.append(sb2));
如果要在并行流上使用它,请执行可变还原(使用stream.collect),因为初始的身份字符串生成器对象可能会意外地从多个线程附加到:
If you're to use this on a parallel stream, please perform a mutable reduction (with stream.collect) as the initial, identity string builder object may otherwise be appended to unpredictably from multiple threads:
StringBuilder returnString = Arrays.stream(s.split(" "))
.collect(StringBuilder::new,
(acc, str) -> acc.append(str.charAt(0)),
StringBuilder::append);
这篇关于如何在Java 1.8的reduce方法内使用StringBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!