如何使用lambda拼接字符串?

我现在有一个List<String> 我想使用lambda把这个list中的字符串全部循环拼接到一个字符串上,lambda可以实现么?该怎么做呢?

蛊毒传说
浏览 1906回答 4
4回答

杨__羊羊

使用foreach对StringBuilder这种有副作用,不大符合函数式编程。可以这样String&nbsp;result&nbsp;=&nbsp;list.stream().collect(Collectors.joining(""));

侃侃无极

StringBuilder str = new StringBuilder();list.forEach(item -> {&nbsp; &nbsp; str.append(item);});补充回答:为什么不能把str改成String类型,通过str = str + item来实现字符串拼接?上面的代码实际上等价于:final StringBuilder str = new StringBuilder();list.forEach(new Consumer<String>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void accept(String item) {&nbsp; &nbsp; &nbsp; &nbsp; str.append(item);&nbsp; &nbsp; }});即Lambda的本质实际上是匿名内部类,所以str必须是final类型(不过代码中的final可以省略),是不可以重新赋值的。

潇潇雨雨

刚看到邀请邮件,抱歉回复晚了,其实上面叉叉哥已经非常非常专业和准确了,但是既然被邀请,感觉不写两句对不起这个邮件,我就把我的一般写法都列出来,感觉我已经进入到回字有几种写法的迂腐境界了。。。希望不要骂我:&nbsp; &nbsp; public static void join1(){&nbsp; &nbsp; &nbsp; &nbsp; List<String> list = Arrays.asList("11","22","23");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //最传统写法:&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder sb = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; for(String s : list){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(s);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(sb.toString());&nbsp; &nbsp; &nbsp; &nbsp; //如果想要加个分隔符,比如逗号,传统写法:&nbsp; &nbsp; &nbsp; &nbsp; sb = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < list.size(); i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(list.get(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i < list.size() - 1){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(",");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(sb.toString());&nbsp; &nbsp; &nbsp; &nbsp; //使用commons-lang库写法, 其实这个已经够简单了,就这个功能而言,我很喜欢,而且最最常用:&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(StringUtils.join(list.toArray(), ","));&nbsp; &nbsp; &nbsp; &nbsp; //进入jdk8时代:&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list.stream().collect(Collectors.joining()));&nbsp; &nbsp; &nbsp; &nbsp; //jdk8时代,加个分隔符:&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list.stream().collect(Collectors.joining(",")));&nbsp; &nbsp; }

海绵宝宝撒

我用rxJava来举例子吧,用java8的Streaming也是一样的:StringBuilder sb = new StringBuilder();rx.Observable.from(list).subscribe(sb::append);如果每个item之间要加入分隔符的话,这次用java8的Streaming哈:String separator = ",";StringBuilder sb = new StringBuilder();Stream.of(list).forEach(item -> sb.append(item).append(separator));sb.deleteCharAt(sb.length() - sepLen);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java