Java 8 – Join or append stream of strings

Learn to join stream of strings with a separator/delimiter using Collectors.joining() API in Java 8.

1. Collectors.joining() method

Java Collectors class has following 3 overloaded static methods for string join operations.

  • joining() – the input elements are concatenated into a String, in encounter order.
  • joining(CharSequence delimiter) – the input elements are concatenated into a String, separated by the specified delimiter, in encounter order.
  • joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) – – the input elements are concatenated into a String, separated by the specified delimiter, with the specified prefix and suffix, in encounter order..

Read More : Java 8 StringJoiner Example

2. Join stream of strings – example

Collectors.joining() method takes separator string as argument and join all the strings in the stream using using this separator.

For example, we use comma as separator then this method will result into a comma-separated string.

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main 
{
	public static void main(String[] args) 
	{
		Stream<String> words = Arrays.asList("A", "B", "C", "D").stream();
		
		String joinedString = words.collect(Collectors.joining());		//ABCD
		
		System.out.println( joinedString );	

		joinedString = words.collect(Collectors.joining(","));		//A,B,C,D
		
		System.out.println( joinedString );

		joinedString = words.collect(Collectors.joining(",", "{", "}"));	//{A,B,C,D}
		
		System.out.println( joinedString );
	}
}

Program output.

ABCD
A,B,C,D
{A,B,C,D}

Drop me your questions related to string joining with java 8 streams.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode