1. Overview
In this short tutorial, we’re going to look at converting an array of strings or integers to a string and back again.
We can achieve this with vanilla Java and Java utility classes from commonly used libraries.
2. Convert Array to String
Sometimes we need to convert an array of strings or integers into a string, but unfortunately, there is no direct method to perform this conversion.
The default implementation of the toString() method on an array returns something like Ljava.lang.String;@74a10858 which only informs us of the object’s type and hash code.
However, the java.util.Arrays utility class supports array and string manipulation, including a toString() method for arrays.
Arrays.toString() returns a string with the content of the input array. The new string created is a comma-delimited list of the array’s elements, surrounded with square brackets (“[]”):
String[] strArray = { "one", "two", "three" }; String joinedString = Arrays.toString(strArray); assertEquals("[one, two, three]", joinedString);
int[] intArray = { 1,2,3,4,5 }; joinedString = Arrays.toString(intArray); assertEquals("[1, 2, 3, 4, 5]", joinedString);
And, while it’s great that the Arrays.toString(int[]) method buttons up this task for us so nicely, let’s compare it to different methods that we can implement on our own.
2.1. StringBuilder.append()
To start, let’s look at how to do this conversion with StringBuilder.append():
String[] strArray = { "Convert", "Array", "With", "Java" }; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < strArray.length; i++) { stringBuilder.append(strArray[i]); } String joinedString = stringBuilder.toString(); assertEquals("ConvertArrayWithJava", joinedString);
Additionally, to convert an array of integers, we can use the same approach but instead call Integer.valueOf(intArray[i]) when appending to our StringBuilder.
2.2. Java Streams API
Java 8 and above offers the String.join() method that produces a new string by joining elements and separating them with the specified delimiter, in our case just empty string:
String joinedString = String.join("", new String[]{ "Convert", "With", "Java", "Streams" }); assertEquals("ConvertWithJavaStreams", joinedString);
Additionally, we can use the Collectors.joining() method from the Java Streams API that joins strings from the Stream in the same order as its source array:
String joinedString = Arrays .stream(new String[]{ "Convert", "With", "Java", "Streams" }) .collect(Collectors.joining()); assertEquals("ConvertWithJavaStreams", joinedString);
2.3. StringUtils.join()
And Apache Commons Lang is never to be left out of tasks like these.
The StringUtils class has several StringUtils.join() methods that can be used to change an array of strings into a single string:
String joinedString = StringUtils.join(new String[]{ "Convert", "With", "Apache", "Commons" }); assertEquals("ConvertWithApacheCommons", joinedString);
2.4. Joiner.join()
And not to be outdone, Guava accommodates the same with its Joiner class. The Joiner class offers a fluent API and provides a handful of helper methods to join data.
For example, we can add a delimiter or skip null values:
String joinedString = Joiner.on("") .skipNulls() .join(new String[]{ "Convert", "With", "Guava", null }); assertEquals("ConvertWithGuava", joinedString);
3. Convert String to Array of Strings
Similarly, we sometimes need to split a string into an array that contains some subset of input string split by the specified delimiter, let’s see how we can do this, too.
3.1. String.split()
Firstly, let’s start by splitting the whitespace using the String.split() method without a delimiter:
String[] strArray = "loremipsum".split("");
Which produces:
["l", "o", "r", "e", "m", "i", "p", "s", "u", "m"]
3.2. StringUtils.split()
Secondly, let’s look again at the StringUtils class from Apache’s Commons Lang library.
Among many null-safe methods on string objects, we can find StringUtils.split(). By default, it assumes a whitespace delimiter:
String[] splitted = StringUtils.split("lorem ipsum dolor sit amet");
Which results in:
["lorem", "ipsum", "dolor", "sit", "amet"]
But, we can also provide a delimiter if we want.
3.3. Splitter.split()
Finally, we can also use Guava with its Splitter fluent API:
List<String> resultList = Splitter.on(' ') .trimResults() .omitEmptyStrings() .splitToList("lorem ipsum dolor sit amet"); String[] strArray = resultList.toArray(new String[0]);
Which generates:
["lorem", "ipsum", "dolor", "sit", "amet"]
4. Conclusion
In this article, we illustrated how to convert an array to string and back again using core Java and popular utility libraries.
Of course, the implementation of all these examples and code snippets can be found over on Github.