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.
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;
I feel like there's a DRYer way to do this. Are there alternate, more efficient approaches here? Thanks!
Edit: Yes I am on Java 8, so Java 8 suggestions are welcome!
In Java 8, you should use something like:
List<String> trimmedStrings =
originalStrings.stream().map(String::trim).collect(Collectors.toList());
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments