join() with Iterables: Joining Collections
What you'll learn: How to use String.join() to convert collections like List and Set into a single delimited string.
Beyond Arrays: Working with Collections
You've seen String.join() work with individual strings, but it also accepts any Iterable as its second parameter. This means you can pass List, Set, ArrayList, LinkedList, or any other collection that implements Iterable directly to join() without converting them to arrays first.
How It Works
The method signature is:
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Think of this like taking a collection of labels and threading them together with a string between each one. You hand join() the entire collection, and it walks through it, inserting your delimiter between elements.
Practical Examples
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");
String result = String.join(", ", fruits);
// result: "apple, banana, cherry"
Works with Set too:
Set<String> colors = new HashSet<>();
colors.add("red");
colors.add("blue");
colors.add("green");
String colorList = String.join(" | ", colors);
// Result varies due to Set ordering: "red | blue | green" or similar
Why This Matters
Before this convenience method, you'd write loops or use StringBuilder with conditionals to avoid trailing delimiters. Now it's a one-liner that works with any collection type you're already using.
Key Takeaway: String.join() accepts any Iterable, letting you convert List, Set, and other collections directly into delimited strings without manual loops or conversion steps.