[英]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)));
Expected output first letter of each word, ie afy
.预期 output 每个单词的首字母,即
afy
。
But getting error at acc.append
, acc
is treated to be a String
.但是在
acc.append
出现错误, acc
被视为String
。
Your use of reduce
is incorrect.您对
reduce
的使用不正确。 The overload you intend to call is the one with 3 parameters, which should also take a binary operator for StringBuilder
:您打算调用的重载是具有 3 个参数的重载,它还应该为
StringBuilder
采用二元运算符:
StringBuilder returnString = Arrays.stream(s.split(" "))
.reduce(new StringBuilder(""),
(acc, str) -> acc.append(str.charAt(0)),
(sb1, sb2) -> sb1.append(sb2));
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:如果您要在并行 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 上使用它,请执行可变归约(使用 stream.collect)作为初始标识字符串构建器 object:否则可能会意外附加到多个线程
StringBuilder returnString = Arrays.stream(s.split(" "))
.collect(StringBuilder::new,
(acc, str) -> acc.append(str.charAt(0)),
StringBuilder::append);
ernest_k's answer is correct, of course.当然, ernest_k 的回答是正确的。 It's worth adding, though, that it seems like you're using
reduce
to implement the joining
collector yourself, and might want to use it directly:不过,值得补充的是,您似乎正在使用
reduce
来自己实现joining
收集器,并且可能希望直接使用它:
String result =
Arrays.stream(s.split(" ")).map(x -> x.substring(0, 1)).collect(Collectors.joining());
You can use reduce
method with String
s instead of StringBuilder
:您可以使用带有
String
s 而不是StringBuilder
的reduce
方法:
String str1 = "apples for you";
String str2 = Arrays
// split string into an array of words
.stream(str1.split("\\s+"))
// first character of a word
.map(str -> str.charAt(0))
// character as string
.map(String::valueOf)
// reduce stream of strings to a single
// string by concatenating them
.reduce((s1, s2) -> s1 + s2)
// otherwise null
.orElse(null);
System.out.println(str2); // afy
See also: Using Streams instead of for loop in java 8另请参阅:在 java 8 中使用 Streams 而不是 for 循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.