如何使用 JAVA 8 Lambda 表达式在 List<String> 中修剪()字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36873239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:57:54  来源:igfitidea点击:

how to trim() String in List<String> using JAVA 8 Lambda expression

javastringlambdajava-8

提问by Sathish Kumar k k

I am looking for all type of string manipulation using java 8 Lambda expressions.

我正在寻找使用 java 8 Lambda 表达式的所有类型的字符串操作。

I first tried the trim()method in simple Stringlist.

我首先尝试了trim()简单String列表中的方法。

String s[] = {" S1","S2 EE ","EE S1 "};
List<String> ls = (List<String>) Arrays.asList(s);
ls.stream().map(String :: trim).collect(Collectors.toList());
System.out.println(ls.toString());

For this example, I was expecting to get [S1, S2 EE, EE S1], but I got [ S1, S2 EE , EE S1 ].

对于这个例子,我期待得到[S1, S2 EE, EE S1],但我得到了[ S1, S2 EE , EE S1 ]

回答by Eran

collect()produces a new List, so you must assign that Listto your variable in order for it to contain the trimmed Strings :

collect()产生一个 new List,因此您必须将其分配List给您的变量,以便它包含修剪后的Strings :

ls = ls.stream().map(String :: trim).collect(Collectors.toList());