DEV Community

Cover image for StringJoiner class provides utility functions to concatenate words
Yasushi Takehara
Yasushi Takehara

Posted on

StringJoiner class provides utility functions to concatenate words

The following code can be improved by StringJoiner class in Java.

String[] names = new String[]{"George", "Sally", "Fred"};
StringBuilder sb = new StringBuilder("[");
for(String name : names){
  sb.append(name).append(":");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
System.out.println(sb.toString()); //=> [George:Sally:Fred]
Enter fullscreen mode Exit fullscreen mode

In the case of StringJoiner class

String[] names = new String[]{"George", "Sally", "Fred"};
StringJoiner sj = new StringJoiner(":", "[", "]");
for(String name : names){
  sj.add(name);
}
System.out.println(sj.toString()); //=> [George:Sally:Fred]
Enter fullscreen mode Exit fullscreen mode

The code has become more concise :-)

Reference
https://cr.openjdk.java.net/~iris/se/11/latestSpec/api/java.base/java/util/StringJoiner.html#

Top comments (0)