StringUtils join() Example in Java

In this post, we are going to see about org.apache.commons.lang3.StringUtils join() Example in Java.

Introduction.

The join() method is used to convert Arrays or Iterable(Collection, List, Set etc.) to String using some separator(for example comma i.e, or any other separator). We need to add below dependency in maven to use org.apache.commons.lang3.StringUtils join() method. We can download apache-commons maven dependency from here.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>

StringUtils join() Example in Java.

There are almost twenty-four overloaded versions of join() method has been defined in org.apache.commons.lang3.StringUtils class. We are going to see a couple of them with an example.

The StringUtils join() is a static method, the return type is String.

First Example.

public static String join(final Iterable<?> iterable, final String separator)

package com.javatute.serviceimpl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class StringUtilsJoin {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("james");
		list.add("rod");
		list.add("duke");
		list.add("jack");

		String s1 = StringUtils.join(list, ",");
		System.out.println(s1);

	}
}

The output is –
james,rod,duke,jack

Second Example.

In this example, we will have String Arrays.

public static String join(final Object[] array, final String separator)

package com.javatute.serviceimpl;

import org.apache.commons.lang3.StringUtils;

public class StringUtilsJoin {
	public static void main(String[] args) {
		String[] stringElements = new String[] { "james", "rod", "duke", "jack" };

		String s1 = StringUtils.join(stringElements, ",");
		System.out.println(s1);
	}
}

Output is –

james,rod,duke,jack

Third Example.

We can use other separators than a comma.

package com.javatute.serviceimpl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

public class StringUtilsJoin {
	public static void main(String[] args) {
		String[] stringElements = new String[] { "james", "rod", "duke", "jack" };

		String s1 = StringUtils.join(stringElements, "+");
		System.out.println("Arrays to String Using plus "+s1);
		
		Set<String> list = new HashSet<>();
		list.add("james");
		list.add("rod");
		list.add("duke");
		list.add("jack");
 
		String s2 = StringUtils.join(list, "+");
		System.out.println("List to String Using plus "+s2);
		
	}
}

Output is –

Arrays to String Using plus james+rod+duke+jack
List to String Using plus duke+rod+james+jack

That’s all about StringUtils join() Example in Java.

You may like.

See Docs here.