Java 修剪() List<String> 中所有元素的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36430727/
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-08-11 17:52:54  来源:igfitidea点击:

What's the best way to trim() all elements in a List<String>?

javalistjava-8

提问by heez

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.

我有一个List<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:

我目前正在遍历列表,为 each调用String.trim()String,并将其添加到新List<String>列表中,然后重新分配回原始列表:

List<String> trimmedStrings = new ArrayList<String)();
for(String s : originalStrings) {
  trimmedStrings.add(s.trim());
}

originalStrings = trimmedStrings;

I feel like there's a DRYerway to do this. Are there alternate, more efficient approaches here? Thanks!

我觉得有一种DRYer方法可以做到这一点。这里有替代的、更有效的方法吗?谢谢!

Edit: Yes I am on Java 8, so Java 8 suggestions are welcome!

编辑:是的,我使用的是 Java 8,因此欢迎提供 Java 8 建议!

采纳答案by Cootri

In Java 8, you should use something like:

在 Java 8 中,你应该使用类似的东西:

List<String> trimmedStrings = 
    originalStrings.stream().map(String::trim).collect(Collectors.toList());

also it is possible to use unary String::trimoperator for elements of the initial list (untrimmed Stringinstances will be overwritten) by calling this method:

也可以通过调用此方法String::trim对初始列表的元素使用一元运算符(未修剪的String实例将被覆盖):

originalStrings.replaceAll(String::trim);

回答by Jonathan Schoreels

If you are on java-8, you can use :

如果您使用的是 java-8,则可以使用:

    final List<Object> result = arrayList.stream()
        .map(String::trim)
        .collect(Collectors.toList());