StringJoiner and String.join()
"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
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);
}
}Navika, Srihitha, Advitha
Pune -> Hyderabad -> Chennai
[Rice, Dal, Ghee]
(no items)How it works
String.join(separator, parts...)puts the separator between the pieces, never before the first or after the last.- It also accepts a whole list (any
Iterableof strings). StringJoinerdoes the same while you add pieces one at a time, and can also add a prefix and suffix around the result, here[and].setEmptyValuechooses what to print when nothing was added. Without it, you'd get[].
Why Not a Loop with +?
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
- Easy: Join the days of the week with
" | ". - Harder: Use a
StringJoinerto build"Marks: {Navika=91; Srihitha=88}"by adding onename=markpiece at a time in a loop.
Key Takeaways
Was this tutorial helpful?