如何在 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
。
但在 acc.append
出现错误,acc
被视为 String
。
您对 reduce
的使用不正确。您打算调用的重载是带有 3 个参数的重载,它还应该为 StringBuilder
:
采用二元运算符
StringBuilder returnString = Arrays.stream(s.split(" "))
.reduce(new StringBuilder(""),
(acc, str) -> acc.append(str.charAt(0)),
(sb1, sb2) -> sb1.append(sb2));
如果您要在并行流上使用它,请执行可变缩减(使用 stream.collect)作为初始标识字符串生成器对象,否则可能会从多个线程不可预测地附加到:
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. It's worth adding, though, that it seems like you're using reduce
to implement the joining
自己收藏,可能想直接使用:
String result =
Arrays.stream(s.split(" ")).map(x -> x.substring(0, 1)).collect(Collectors.joining());
您可以将 reduce
方法与 String
一起使用,而不是 StringBuilder
:
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
另请参阅:
String s = "apples for you";
StringBuilder returnString = new StringBuilder("");
Arrays.stream(s.split(" "))
.reduce(returnString, (acc, str) -> acc.append(str.charAt(0)));
期望输出每个单词的第一个字母,即afy
。
但在 acc.append
出现错误,acc
被视为 String
。
您对 reduce
的使用不正确。您打算调用的重载是带有 3 个参数的重载,它还应该为 StringBuilder
:
StringBuilder returnString = Arrays.stream(s.split(" "))
.reduce(new StringBuilder(""),
(acc, str) -> acc.append(str.charAt(0)),
(sb1, sb2) -> sb1.append(sb2));
如果您要在并行流上使用它,请执行可变缩减(使用 stream.collect)作为初始标识字符串生成器对象,否则可能会从多个线程不可预测地附加到:
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. It's worth adding, though, that it seems like you're using reduce
to implement the joining
自己收藏,可能想直接使用:
String result =
Arrays.stream(s.split(" ")).map(x -> x.substring(0, 1)).collect(Collectors.joining());
您可以将 reduce
方法与 String
一起使用,而不是 StringBuilder
:
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
另请参阅: