What is StringJoiner class in Java 8?



The StringJoiner class in Java 8 constructs a sequence of characters. This sequence is separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

The following are the constructors of the StringJoiner class:

  • StringJoiner(CharSequence delimiter): This constructor constructs a StringJoiner with no characters in it and with no prefix or suffix. It used the copy of the supplied delimiter.

  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) This constructor constructs a StringJoiner with no characters in it. It uses the copies of the supplied prefix, delimiter and suffix.

The syntax is as follows:

public final class StringJoiner extends Object

Here, class Object is the root of the class hierarchy.

To work with the StringJoiner in Java 8, import the following package:

import java.util.StringJoiner;

The following is an example to implement StringJoiner method in Java. We have used comma as the delimiter here:

Example

 Live Demo

import java.util.StringJoiner; public class Demo {    public static void main(String[] args) {       StringJoiner strJoin = new StringJoiner(",");       strJoin.add("One");       strJoin.add("Two");       strJoin.add("Three");       strJoin.add("Four");       strJoin.add("Five");       strJoin.add("Six");       strJoin.add("Seven");       System.out.println(strJoin.toString());    } }

output

One,Two,Three,Four,Five,Six,Seven
Updated on: 2019-07-30T22:30:25+05:30

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements