Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
stringjoiner
communitycreator

What is StringJoiner in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In Java, we can use StringJoiner to join strings with a separator. We can also choose to specify the prefix and suffix added to the result strings.

Syntax

StringJoiner(CharSequence delimiter)
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

To use StringJoiner, create a StringJoinerobject and call the add method by passing the string to be joined.

Code

import java.util.StringJoiner;
class JoinString {
public static void main( String args[] ) {
StringJoiner joiner = new StringJoiner(", ");
joiner.add("I");
joiner.add("Love")
.add("Badminton");
System.out.println(joiner.toString());
}
}

In the code above, we:

  • Created a StringJoiner with , as the separator of the string.

  • Used the add() method to add some strings to the StringJoiner. This method returns the reference to the StringJoiner to chain the add() method.

  • Called the toString() method to convert the StringJoiner into a string. The resultant string is the joined version of all strings separated by the separator.

Example with prefix and suffix

import java.util.StringJoiner;
class JoinString {
public static void main( String args[] ) {
String SEPARATOR = "-";
String PREFIX = "{";
String SUFFIX = "}";
StringJoiner joiner;
joiner = new StringJoiner(SEPARATOR, PREFIX, SUFFIX);
joiner.add("I");
joiner.add("Love")
.add("Badminton");
System.out.println(joiner.toString());
}
}

In the code above, we created a StringJoiner named joiner with - as a separator, { as PREFIX, and } as SUFFIX.

The resulting string will start with {, end with }, and the separator - will be added between the strings.

RELATED TAGS

java
string
stringjoiner
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring