我现在有一个List<String> 我想使用lambda把这个list中的字符串全部循环拼接到一个字符串上,lambda可以实现么?该怎么做呢?
伊谢尔伦2017-04-17 17:51:11
Using foreach has side effects on StringBuilder, which is not in line with functional programming. It can be like this
String result = list.stream().collect(Collectors.joining(""));
PHP中文网2017-04-17 17:51:11
StringBuilder str = new StringBuilder();
list.forEach(item -> {
str.append(item);
});
Supplementary answer: Why can't str be changed to String type and string splicing can be achieved through str = str + item
?
The above code is actually equivalent to:
final StringBuilder str = new StringBuilder();
list.forEach(new Consumer<String>() {
@Override
public void accept(String item) {
str.append(item);
}
});
That is, the essence of Lambda is actually an anonymous inner class, so str must be a final type (but the final in the code can be omitted) and cannot be reassigned.
巴扎黑2017-04-17 17:51:11
I just saw the invitation email, and I’m sorry for the late reply. In fact, Brother Chacha above was very, very professional and accurate, but since I was invited, I felt sorry for not writing a few sentences in this email, so I’ll just write it in my usual way. Listing them out, I feel like I have entered the pedantic realm of writing the word "hui" in several ways. . . I hope you won’t scold me:
public static void join1(){
List<String> list = Arrays.asList("11","22","23");
//最传统写法:
StringBuilder sb = new StringBuilder();
for(String s : list){
sb.append(s);
}
System.out.println(sb.toString());
//如果想要加个分隔符,比如逗号,传统写法:
sb = new StringBuilder();
for(int i = 0; i < list.size(); i++){
sb.append(list.get(i));
if(i < list.size() - 1){
sb.append(",");
}
}
System.out.println(sb.toString());
//使用commons-lang库写法, 其实这个已经够简单了,就这个功能而言,我很喜欢,而且最最常用:
System.out.println(StringUtils.join(list.toArray(), ","));
//进入jdk8时代:
System.out.println(list.stream().collect(Collectors.joining()));
//jdk8时代,加个分隔符:
System.out.println(list.stream().collect(Collectors.joining(",")));
}
迷茫2017-04-17 17:51:11
I’ll use rxJava as an example. It’s the same with java8’s Streaming:
StringBuilder sb = new StringBuilder();
rx.Observable.from(list).subscribe(sb::append);
If you want to add a separator between each item, use java8's Streaming this time:
String separator = ",";
StringBuilder sb = new StringBuilder();
Stream.of(list).forEach(item -> sb.append(item).append(separator));
sb.deleteCharAt(sb.length() - sepLen);