Search code examples
javatrim

How should I map a function onto a string array in java?


I want to split a string and trim each word in the newly established array. Is there a simple (functional) way in Java how to do it as a one liner without the use of a cycle?

String[] stringarray = inputstring.split(";");
for (int i = 0; i < stringarray.length; i++) { 
    stringarray[i] = stringarray[i].trim(); 
}

EDIT: corrected the cycle (Andreas' comment)


Solution

  • You can do it in the following way:

    String[] stringarray = inputstring.trim().split("\\s*;\\s*");
    

    Explanation of the regex:

    1. \s* is zero or more times whitespace
    2. \s*;\s* specifies zero or more times whitespace followed by ; which may be followed by zero or more times whitespace