Convert String to Array in Java

Convert String to Array in java

When developing applications in Java there are many cases where we will find ourselves converting data from one type to the other.

Developers must understand how this is done because it will enhance their system effectiveness leading to ease of use from different users interacting with the system.

How to convert String to Array in Java

In this tutorial, we will learn how to convert String to array in Java and an example use case in an application is when we want to break the input search into several sequences and return results based on a sequence that matches a record from our data source.

A String is a data type that is implemented by a sequence of characters in double-quotes such as "Hello! World" while an array is a data structure that allows us to insert, traverse, delete, and search elements of a particular data type.

Using toArray() method of Set

A Set is a collection that only supports unique elements and it provides us with a method that we can leverage to convert a string to an array.

This method is called toArray() and is a generic method which means it can also be applied to other data types in Java.

To achieve this we will create a new array of size 0 and pass it to this method. The collection of elements in the Set will be added to this array and the method will return an array containing our elements.

Note that if the array created is less than the size of the collection the method creates a new array with the same size as the collection to accommodate all the values and returns the new array.

If the size of the array is large than the size of the collection the remaining storage locations are set to null.

The type of array returned by this method is of the same type as that of the specified array and the method throws an ArrayStoreException if the specified array type is not a supertype of every element in the collection.

The method also throws a NullPointerException if the specified array is null.

Output:

[Kangaroos are not dangerous, Kangaroos live in australia]

Using the split() method of String class

The split() method of the Stringg class uses a regular expression to split the string by every string that matches the specified regular expression.

The splitting is done by terminating a string with another substring that matches the given regular expression.

The method returns an array consisting of the terminated substrings and the elements are arranged in the order they appear in the original string.

If the regular expression does not match any substring the resulting array has only one element which is this string.

If the regular expressions syntax cannot be recognized the method throws a PatternSyntaxException.

Output:

[Kangaroos, live, in, australia]

Using StringTokenizor class

From the name of the class, we can conclude that this class provides the functionality to break a string into tokens.

Tokens is a term mostly in programming to refer to a single element such as an identifier, keyword, constants, operators, and separators.

Note that the StringTokenizer cannot differentiate between identifiers, numbers, quoted strings, or how to jump comments but uses delimiters to break the string into tokens.

We will use this functionality to convert our string to an array by fetching each token obtained from our string and adding it to a new array.

Since we want to break our string using a whitespace delimiter, we will pass string whitespace in the second parameter of the StringTokenizer.

The size of our array will be managed by the countTokens() method of the StringTokenizer that returns an int value indicating the number of tokens that are remaining in the string.

We will use a while loop that will consume the hasMoreTokens() method checks if there are more tokens in the string and returns true if there is at least one element and false otherwise.

When the condition evaluates to true we use the nextToken() method to get the next element and add it to our new array.

A counter starting from 0 is used to increment the loop and we also use the counter value as the index of the element in our array.

Note that the use of StringTokenizer is discouraged in new code and it is only maintained for compatibility reasons because it is a legacy class.

The split() method which is discussed in this tutorial, should be used as an alternative to achieving similar functionality.

Output:

[Kangaroos, live, in, australia]

Using the split() method of StringUtils class

Thie StringUtils class is part of the apache commons library and we have to add it to our application by downloading the library and adding it to our classpath or adding a dependency to our project object model file (pom.xml) if on a Maven environment.

The StringUtils class provides a static method that returns an array of strings by providing two parameters, the first being the original string and the second being the character used to split the string.

We will split our string using the whitespace separators by passing a whitespace string in the second parameter as shown below.

Output:

[Kangaroos, live, in, australia]

Using split() method of Pattern class

The split() method of Pattern class works the same way as that of the String class apart from the fact that the regular expression provided must first be compiled to an instance of this class.

For example, if we provide the regular expression \s it will be compiled to \t\n\x0B\f\r and used by the matcher class to match the provided string with the compiled regular expression.

If the match returns true, the string will be split at this point and a new array containing our substrings returned.

Since the compile() and split() are static and the compile method returns a Pattern we can chain the split method to the compile method which helps make our code cleaner.

Output:

[Kangaroos, live, in, australia]

Conclusion

In this tutorial, we have learned how to convert a String to an array by implementing five solutions which include using the toArray() method of Set, using StringTokenizor class, using the split() method of StringUtils class, using the split() method of String class, and concluded with using split() method of Pattern class.

That’s all about how to convert String to array in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *