join() is a StringUtils class that is used to join the elements of the provided array/iterable/iterator/varargs into a single string containing the provided list of elements.
StringUtilsThe definition of StringUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the StringUtils class as follows:
import org.apache.commons.lang3.StringUtils;
public static String join(final Object[] array, final char delimiter, final int startIndex, final int endIndex)
final Object[] array: The array of values to join.final char delimiter: The delimiter character to use.final int startIndex: The first index to start joining from.final int endIndex: The last index to stop joining from (exclusive).This method returns the joined string with the delimiter.
For the overloaded methods, refer here.
import org.apache.commons.lang3.StringUtils;import java.util.Arrays;public class Main{public static void main(String[] args) {// Example 1String[] strings = {"hello", "educative", "edpresso"};char sep = '-';System.out.printf("StringUtils.join('%s', %s) = '%s'", Arrays.toString(strings), sep, StringUtils.join(strings, sep));System.out.println();// Example 2strings = new String[]{"hello", null, "edpresso"};sep = '-';System.out.printf("StringUtils.join('%s', %s) = '%s'", Arrays.toString(strings), sep, StringUtils.join(strings, sep));System.out.println();}}
The output of the code will be as follows:
StringUtils.join('[hello, educative, edpresso]', -) = 'hello-educative-edpresso'
StringUtils.join('[hello, null, edpresso]', -) = 'hello--edpresso'
strings = ["hello", "educative", "edpresso"]separator = "-"The method returns hello-educative-edpresso joining all the elements with - as the separator.
strings = ["hello", null, "edpresso"]separator = "-"The method returns hello--edpresso. null elements are treated as empty strings.
Free Resources