Convert java.util.stream.Stream to String using Collectors.joining()

Collectors joining() method can be used along with Stream collect() operation to convert Stream to a String.

java 8 stream collectors.joining()

Following overloaded joining() methods are useful to convert elements to strings and concatenate them.
 

Collectors.joining()

Collectors.joining() returns a Collector that concatenates the input elements into a String, in the provided order.

Syntax :


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

This method returns a Collector that concatenates the input elements into a String, in encounter order

Example : Collectors.joining()

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

public class StreamDemo {

  public static void main(String[] args) {
    String str = Stream.of("Hello","World").collect(Collectors.joining());
    System.out.println(str);
  }

}

Output:

HelloWorld

 

Collectors.joining() with delimiter

We can also provide a delimiter to Collectors.joining() to concatenate the input elements into a String, separated by the specified delimiter in the provided order.

Syntax :


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

This returns a Collector which concatenates CharSequence elements, separated by the specified delimiter, in encounter order.

Example : Collectors.joining() with delimiter

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

public class StreamDemo {

  public static void main(String[] args) {
    // If you want to join the strings by a delimiter, you can pass the delimiter to the Collectors.joining()
    //Example : Convert Stream to String with delimiter colon(:)
    
    String emp = Stream.of("John Doe", "Engineer").collect(Collectors.joining(":"));
    System.out.println(emp);
  }

}

Output:

John Doe:Engineer

 

Collectors.joining() with delimiter along with prefix and suffix

Syntax :


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

This method returns a Collector which concatenates CharSequence elements, separated by the specified delimiter, in encounter order

Example : Collectors.joining() with delimiter along with prefix and suffix

  String emp = Stream.of("John Doe", "Engineer").collect(Collectors.joining(":","Mr ", ", TopJavatutorial"));
  System.out.println(emp);

Output:

Mr John Doe:Engineer, TopJavatutorial

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags