1. Overview
1.概述
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.
我们可以通过vanilla Java和常用库中的Java实用类来实现这一目标。
2. Convert Array to String
2.将数组转换为字符串
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.
数组上的toString()方法的默认实现会返回类似Ljava.lang.String;@74a10858的东西,它只告知我们对象的类型和哈希代码。
However, the java.util.Arrays utility class supports array and string manipulation, including a toString() method for arrays.
然而,java.util.Arrays实用类支持数组和字符串操作,包括一个用于数组的toString()方法。
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 (“[]”):
Arrays.toString()返回一个包含输入数组内容的字符串。创建的新字符串是一个以逗号分隔的数组元素列表,周围有方括号(”[]”)。
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.
虽然Arrays.toString(int[])方法为我们很好地完成了这项任务,但让我们把它与我们可以自己实现的不同方法进行比较。
2.1. StringBuilder.append()
2.1 StringBuilder.append()
To start, let’s look at how to do this conversion with StringBuilder.append():
首先,让我们看看如何用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.
此外,要转换一个整数数组,我们可以使用同样的方法,但在追加到我们的StringBuilder时调用Integer.valueOf(intArray[i]) 。
2.2. Java Streams API
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:
Java 8及以上版本提供了String.join()方法,该方法通过连接元素并以指定的分隔符(在我们的例子中只是空字符串)来产生一个新字符串。
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:
此外,我们可以使用Java Streams API中的Collectors.join()方法,该方法将Stream中的字符串按照与其源数组相同的顺序进行连接。
String joinedString = Arrays
.stream(new String[]{ "Convert", "With", "Java", "Streams" })
.collect(Collectors.joining());
assertEquals("ConvertWithJavaStreams", joinedString);
2.3. StringUtils.join()
2.3. StringUtils.join()
And Apache Commons Lang is never to be left out of tasks like these.
而Apache Commons Lang是永远不会被排除在这样的任务之外的。
The StringUtils class has several StringUtils.join() methods that can be used to change an array of strings into a single string:
StringUtils类有几个StringUtils.join()方法,可以用来将一个字符串数组变成一个单一的字符串。
String joinedString = StringUtils.join(new String[]{ "Convert", "With", "Apache", "Commons" });
assertEquals("ConvertWithApacheCommons", joinedString);
2.4. Joiner.join()
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.
Guava也不甘示弱,通过其Joiner类来实现。Joiner类提供了一个流畅的API,并提供了少量的辅助方法来连接数据。
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
3.将字符串转换为字符串数组
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()
3.1.String.split()
Firstly, let’s start by splitting the whitespace using the String.split() method without a delimiter:
首先,让我们开始使用String.split()方法分割空白,而不使用分隔符。
String[] strArray = "loremipsum".split("");
Which produces:
这就产生了。
["l", "o", "r", "e", "m", "i", "p", "s", "u", "m"]
3.2. StringUtils.split()
3.2. StringUtils.split()
Secondly, let’s look again at the StringUtils class from Apache’s Commons Lang library.
其次,让我们再看一下Apache的Commons Lang库中的StringUtils类。
Among many null-safe methods on string objects, we can find StringUtils.split(). By default, it assumes a whitespace delimiter:
在许多关于字符串对象的空安全方法中,我们可以找到StringUtils.split()。默认情况下,它假设了一个空白分隔符。
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()
3.3.Splitter.split()
Finally, we can also use Guava with its Splitter fluent API:
最后,我们还可以使用Guava的Splitter流畅的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
4.总结
In this article, we illustrated how to convert an array to string and back again using core Java and popular utility libraries.
在这篇文章中,我们说明了如何使用核心Java和流行的工具库将数组转换为字符串,然后再转换回来。
Of course, the implementation of all these examples and code snippets can be found over on GitHub.
当然,所有这些例子和代码片断的实现都可以在GitHub上找到over。