Java - Split and trim in one shot

If there is no text between the commas, the following expression will not create empty elements:

String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");

Using java 8 you can do it like this in one line

String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);

Use regular expression \s*,\s* for splitting.

String result[] = attributes.split("\\s*,\\s*");

For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:

String result[] = attributes.trim().split("\\s*,\\s*");

Tags:

Java

String

Split