英文 名 称 【Array to String Conversions】

An overview of the

The content of this page provides some instructions on how to convert arrays and strings to each other.

We can use native Java (Vanilla Java) or some third-party Java utility class to implement this transformation. ies.

Convert Array to String

Sometimes we want to convert an array of string numbers or integers into a string. But if we just use

toString()

To convert, you might get something like the following

Ljava.lang.String; @74a10858

String of.

The string above shows the type of the object and the current hash code for the object.

However,

java.util.Arrays

The utility class can also support some toString() methods to convert an Array to a String.

Arrays.tostring () converts the input array to a string, which is separated by commas and preceded by square brackets [].

You can examine the following code:

        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);
Copy the code

Append () method of StringBuilder

This is a native Java-based implementation that allows you to iterate over the array to be converted and append the result to the string using the append() method.

        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);
Copy the code

Alternatively, if the data stored in your array is an integer, you can use the method conversion function to first convert the integer type to a string and then add it.

Java Streams API

From Java 8 and above, you can join the given array elements together using different join strings using the string.join () method. In our use case, we joined them using whitespace characters.

        String joinedString = String.join("", new String[]{"Convert", "With", "Java", "Streams"});
        assertEquals("ConvertWithJavaStreams", joinedString);
Copy the code

More importantly, we can use the Java Streams API

Collectors.joining()

Method, which will retain the same order as the input data.

        String joinedString = Arrays
                .stream(new String[]{"Convert", "With", "Java", "Streams"})
                .collect(Collectors.joining());
        assertEquals("ConvertWithJavaStreams", joinedString);
Copy the code

StringUtils.join()

The Apache Commons Lang provides a great way to handle strings, which helps us solve the above problem.

The join method automatically merges the input data in the same order as you entered the data.

        String joinedString = StringUtils.join(new String[]{"Convert", "With", "Apache", "Commons"});
        assertEquals("ConvertWithApacheCommons", joinedString);
Copy the code

Joiner.join()

The same Guava also provides the same utility classes to use.

For example, we can use the following code to concatenate an array.

String joinedString = Joiner.on("")
        .skipNulls()
        .join(new String[]{ "Convert", "With", "Guava", null });
assertEquals("ConvertWithGuava", joinedString);
Copy the code

Convert strings to arrays

Similarly, there are times when we want to be able to convert strings into arrays.

The most common case is that we have an input string with a specific delimiter, and we need to split the string into arrays based on the position of the delimiter.

String.split()

This is the simplest way to split a string using the given characters, as follows:

String[] strArray = "loremipsum".split("");
Copy the code

The above code will produce the following output, since we are not given any delimiters, the method will be split by character.

["l", "o", "r", "e", "m", "i", "p", "s", "u", "m"]
Copy the code

StringUtils.split()

Also, probably the most used is Apache Commons

StringUtils

, this can split the specified string.

If you use String to split objects, you may run into empty object problems. For example, if you enter an empty String, the native method of String will throw a null exception.

The StringUtils method is used to avoid empty object exceptions, so this utility class is very common. By default, this method uses a space as a separator.

String[] splitted = StringUtils.split("lorem ipsum dolor sit amet");
Copy the code

The above method will print the following array.

["lorem", "ipsum", "dolor", "sit", "amet"]
Copy the code

Splitter.split()

Finally, you can also use Guava’s split API, and if Apache Commons provides methods, Guava usually provides similar ones.

For example, we can use the following method to split, as you can see, we can split the result at the same time.

List<String> resultList = Splitter.on(' ')
    .trimResults()
    .omitEmptyStrings()
    .splitToList("lorem ipsum dolor sit amet");   
String[] strArray = resultList.toArray(new String[0]);
Copy the code

The above code produces the following result:

["lorem", "ipsum", "dolor", "sit", "amet"]
Copy the code

conclusion

This page provides some explanation of how to convert between String and Array. It is generally possible to use native methods for conversion, but we generally do not recommend using them because of the poor functionality of the methods and the high susceptibility to empty object exceptions.

Therefore, it is recommended to use Apache Commons or Guava’s related methods for conversion.

www.ossez.com/t/java-arra…