I was just wondering what the best way to remove the white space from all the elements of a list would be.
For example if I had String [] array = {" String", "Tom Selleck "," Fish "}
How could I get all the elements as {"String","Tom Selleck","Fish"}
Thanks!
In Java 8,
Arrays.parallelSetAll
seems ready made for this purpose:This will modify the original array in place, replacing each element with the result of the lambda expression.
Add commons-lang3-3.1.jar in your application build path. Use the below code snippet to trim the String array.
You can just iterate over the elements in the array and call
array[i].trim()
on each elementTry this:
Now
trimmedArray
contains the same strings asarray
, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:I know this is a really old post, but since Java 1.8 there is a nicer way to trim every String in an array.
Java 8 Lamda Expression solution:
with this solution you don't have to create a new Array.
Like in Óscar López's solution