修剪List()< String> ;?中所有元素的最佳方法是什么? [英] What's the best way to trim() all elements in a List<String>?
问题描述
我有列表< String>
,可能包含数千个字符串。我正在实现一个验证方法,其中包括确保每个字符串中没有任何前导或尾随空格。
I have a List<String>
, potentially holding thousands of strings. I am implementing a validation method, which includes ensuring that there aren't any leading or trailing whitespaces in each string.
我正在迭代列表,调用< a href =https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim-- =noreferrer> String.trim() for每个字符串
,并将其添加到新的列表< String>
,然后重新分配回原始列表:
I'm currently iterating over the list, calling String.trim() for each String
, and adding it to a new List<String>
and reassigning back to the original list after:
List<String> trimmedStrings = new ArrayList<String)();
for(String s : originalStrings) {
trimmedStrings.add(s.trim());
}
originalStrings = trimmedStrings;
我觉得有一个 DRYer 这样做的方法。这里有替代的,更有效的方法吗?谢谢!
I feel like there's a DRYer way to do this. Are there alternate, more efficient approaches here? Thanks!
编辑:是的我在Java 8上,所以欢迎Java 8建议!
Yes I am on Java 8, so Java 8 suggestions are welcome!
推荐答案
在Java 8中,你应该使用类似的东西:
In Java 8, you should use something like:
List<String> trimmedStrings =
originalStrings.stream().map(String::trim).collect(Collectors.toList());
也可以使用一元 String :: trim
b
$ b
also it is possible to use unary String::trim
operator for elements of the initial list (untrimmed String
instances will be overwritten) by calling this method:
originalStrings.replaceAll(String::trim);
这篇关于修剪List()< String> ;?中所有元素的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!