Sobes.tech
Middle

What is StringJoiner in Java?

sobes.tech AI

Answer from AI

StringJoiner is a class in Java 8 designed for convenient and efficient string construction by joining multiple elements with a specified delimiter, as well as the ability to specify a prefix and suffix for the final string.

Main advantages:

  • Simple API for string building.
  • Automatic delimiter management (does not add a delimiter after the last element).
  • Allows easy setting of prefix and suffix.
  • More efficient than string concatenation in a loop using the + operator.

Example of usage:

// Create a StringJoiner with delimiter ", "
StringJoiner stringJoiner = new StringJoiner(", ");
stringJoiner.add("apple");
stringJoiner.add("banana");
stringJoiner.add("orange");
String result = stringJoiner.toString(); // result: "apple, banana, orange"

Example with prefix and suffix:

// Create a StringJoiner with delimiter "-", prefix "[" and suffix "]"
StringJoiner stringJoinerWithBounds = new StringJoiner("-", "[", "]");
stringJoinerWithBounds.add("one");
stringJoinerWithBounds.add("two");
String resultWithBounds = stringJoinerWithBounds.toString(); // resultWithBounds: "[one-two]"

The merge() method allows combining two StringJoiner objects.

StringJoiner sj1 = new StringJoiner(",", "{", "}");
sj1.add("A").add("B"); // sj1: "{A,B}"

StringJoiner sj2 = new StringJoiner(":");
sj2.add("C").add("D"); // sj2: "C:D"

StringJoiner merged = sj1.merge(sj2); // merged: "{A,B,C:D}"