StringJoiner and String.join()

Naveen AnamaneniUpdated · 3 min read
easyJava 25javastrings

"Navika, Srihitha, Advitha": three names with a comma between each pair, but not after the last one. Writing that with a loop and + means checking "is this the last item?" every time, and it's easy to end up with a stray comma. String.join and StringJoiner handle the separators for you, so the commas always land in the right places.

Joining with a Separator

Join.java▶ Try it
import java.util.List;
import java.util.StringJoiner;
 
public class Join {
    public static void main(String[] args) {
        System.out.println(String.join(", ", "Navika", "Srihitha", "Advitha"));
 
        List<String> cities = List.of("Pune", "Hyderabad", "Chennai");
        System.out.println(String.join(" -> ", cities));
 
        StringJoiner list = new StringJoiner(", ", "[", "]");
        list.add("Rice").add("Dal").add("Ghee");
        System.out.println(list);
 
        StringJoiner empty = new StringJoiner(", ", "[", "]");
        empty.setEmptyValue("(no items)");
        System.out.println(empty);
    }
}
Output
Navika, Srihitha, Advitha
Pune -> Hyderabad -> Chennai
[Rice, Dal, Ghee]
(no items)

How it works

  1. String.join(separator, parts...) puts the separator between the pieces, never before the first or after the last.
  2. It also accepts a whole list (any Iterable of strings).
  3. StringJoiner does the same while you add pieces one at a time, and can also add a prefix and suffix around the result, here [ and ].
  4. setEmptyValue chooses what to print when nothing was added. Without it, you'd get [].

Why Not a Loop with +?

The hand-written way
String result = "";
for (int i = 0; i < names.length; i++) {
    result += names[i];
    if (i < names.length - 1) {
        result += ", ";            // easy to get wrong
    }
}

It works, but it needs an index, an extra condition and, with += in a loop, it's slow for big lists. String.join(", ", names) says the same in one line.

Common Mistakes

Building lists with += and trimming the last comma afterwards. Use String.join.

Passing numbers to String.join. It needs strings; convert them first with String.valueOf.

Forgetting setEmptyValue. An empty joiner with a prefix and suffix prints just the brackets.

Practice

  1. Easy: Join the days of the week with " | ".
  2. Harder: Use a StringJoiner to build "Marks: {Navika=91; Srihitha=88}" by adding one name=mark piece at a time in a loop.

Quick check: Joining

4 questions
1What does String.join("-", "a", "b", "c") return?
2What do the second and third arguments of new StringJoiner(", ", "[", "]") set?
3What prints for an empty StringJoiner(", ", "[", "]") with no empty value set?
4Which method sets the text for an empty joiner?

Key Takeaways

Was this tutorial helpful?

Lesson 202 of 482