Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Friday, November 26, 2021

Java 8 Streams - Join or Append Stream of Strings using Collectors.joining()

1. Overview

In this tutorial, We'll learn how to append or join a list of strings or stream of strings in java 8.

This joining is done with a specific delimiter or separator with the Collectors api method.

Use Collectors.joining() method joins the values of the stream with a delimiter specified. If the delimiter is not specified then it takes nothing as a separator. So, that final returned string will be having just all values concatenated from the stream.

Along with the joining, this method does the conversion from java 8 stream to string object with the default delimiter.

Java 8 Stream Join String


2. Collectors.joining() Method


Collectors.joining() method does concatenate the list of values or list of strings or stream of values or strings into a new string. 

For this method, we can pass the our own delimiter and and also we can supply the prefix, suffix to the output string.

joining() is an overloaded method and available in 3 versions.

public static Collector<CharSequence,?,String> joining()
public static Collector<CharSequence,?,String> joining(CharSequence delimiter)
public static Collector<CharSequence,?,String> joining(CharSequence delimiter,
                                                       CharSequence prefix,
                                                       CharSequence suffix)


joining(): Input elements are concatenated into a new String as encounter order in the stream.

joining(CharSequence delimiter): Input elements are concatenated into a new String with the given delimiter value as encounter order in the stream.

joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Input elements are concatenated into a new String with the given delimiter, suffix and prefix values as encounter order in the stream.


3. Java 8 Stream Join String Examples


Next, let us write the example programs using all these 3 methods of Collectors.joining().

Below example program does the stream joining as string and converting stream to string.

package com.javaprogramto.java8.streams.join;

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

/**
 * Java Join Stream Of Strings and stream to string examples.
 * 
 * @author JavaProgramTo.com
 *
 */
public class StreamOfStringJoiningExample {

	public static void main(String[] args) {

		// Creating the List with string values using Arrays.asList() method
		List<String> stringsList = Arrays.asList("1", "2", "3", "4", "5");

		// java 8 join stream of strings or stream to string

		// Example - 1: with default delimiter
		String joinWithDefaultDelimiter = stringsList.stream().collect(Collectors.joining());

		// Example - 2: with delimiter
		String joinWithDelimiter = stringsList.stream().collect(Collectors.joining(":"));

		// Example - 3: with given delimiter, suffix and prefix
		String joinWithDelimiterSuffixPrefix = stringsList.stream().collect(Collectors.joining("|", "[", "]"));

		// printing the values
		System.out.println("Input List of strings : " + stringsList);
		System.out.println("joining() string : " + joinWithDefaultDelimiter);
		System.out.println("joining(delimiter) string : " + joinWithDelimiter);
		System.out.println("joining(delimiter, suffix, prefix) string : " + joinWithDelimiterSuffixPrefix);
	}
}

Output:
Input List of strings : [1, 2, 3, 4, 5]
joining() string : 12345
joining(delimiter) string : 1:2:3:4:5
joining(delimiter, suffix, prefix) string : [1|2|3|4|5]

From the output, we can observe the output from 3 methods with default delimiter, custom delimiter and with a prefix and suffix values.


4. Stream IllegalStateException: stream has already been operated upon or closed


In the above program, we have created the new stream every time we call collect() or joining() method. You may think, can we reuse the stream object for the next two calls. Thats mean first create the Stream object once using stream() method and use the same stream object for all joining() calls.

Look the below code and the output.

		// Creating the stream object once and reuse for every collect() call.
		Stream<String> stream = stringsList.stream();

		// java 8 join stream of strings or stream to string
		
		// Example - 1: with default delimiter
		String joinWithDefaultDelimiter = stream.collect(Collectors.joining());

		// Example - 2: with delimiter
		String joinWithDelimiter = stream.collect(Collectors.joining(":"));
		
		// Example - 3: with given delimiter pipe(|), suffix and prefix
		String joinWithDelimiterSuffixPrefix = stream.collect(Collectors.joining("|", "[", "]"));


Output:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
	at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
	at com.javaprogramto.java8.streams.join.StreamOfStringJoiningExample.main(StreamOfStringJoiningExample.java:29)

We got the runtime exception because once the terminal method collect() is called stream will be closed. In the next step, we are trying to call collect() method on the closed stream.

We have already discussed in detail about the error "stream has already been operated upon or closed" and how can be handled using Supplier.


5. Conclusion


In this article, We've seen how to join the stream of strings and how to convert Stream to String in java 8 with help of the joining() method.




Ref 

No comments:

Post a Comment

Please do not add any spam links in the comments section.