Java StringJoiner Example

1. Introduction

The StringJoiner class in Java is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. This is particularly useful in applications where you need to build a string from multiple parts, such as in SQL query construction or generating a formatted message.

Key Points

- StringJoiner is part of java.util package.

- It allows adding strings with a specified delimiter.

- Prefix and suffix can be added to the entire sequence.

- It simplifies the joining of multiple string elements in a readable manner.

2. Program Steps

1. Create an instance of StringJoiner with a delimiter.

2. Optionally specify a prefix and a suffix.

3. Add strings to the StringJoiner.

4. Convert the StringJoiner to a string for output.

3. Code Program

import java.util.StringJoiner; public class StringJoinerExample { public static void main(String[] args) { // Create a StringJoiner with a comma as delimiter, and square brackets as prefix and suffix StringJoiner joiner = new StringJoiner(", ", "[", "]"); // Add elements joiner.add("Apple"); joiner.add("Banana"); joiner.add("Cherry"); joiner.add("Date"); // Convert to String String result = joiner.toString(); // Print the result System.out.println(result); } } 

Output:

[Apple, Banana, Cherry, Date] 

Explanation:

1. StringJoiner joiner = new StringJoiner(", ", "[", "]"): Initializes a StringJoiner with a comma and space as the delimiter and square brackets as the prefix and suffix.

2. joiner.add("Apple"); joiner.add("Banana"); joiner.add("Cherry"); joiner.add("Date");: Adds four strings to the StringJoiner.

3. String result = joiner.toString(): Converts the StringJoiner content to a String.

4. System.out.println(result): Outputs the string representation of the StringJoiner, showing the strings joined by commas and enclosed in square brackets.


Comments