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!
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Parameter: It does not accepts any parameter. Return Value: It does not returns any value.
ForEach(x => x = x. Trim(). TrimStart().
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)
Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.
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);
If you are on java-8, you can use :
final List<Object> result = arrayList.stream()
.map(String::trim)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With