The join() method of String class is introduced in Java 8. This method is used to concatenate strings with specified delimiter. It is also used to combine multiple elements of a collection with the specified separator. In this guide, we will see several programs to discuss Java String join() method.
Note: Java 8 also introduced a new StringJoiner class for the same purpose.
Syntax
There are two main overloaded versions of the String.join()
method:
Joining CharSequence elements
public static String join(CharSequence delimiter,
CharSequence... elements)
Joining Iterable elements
public static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements)
Parameters
- delimiter: The delimiter that separates each element, for example comma(,), space(” “) etc. are delimiters.
- elements: The sequence of elements to be joined.
Examples of Java String join() method
1. Joining Strings with a Delimiter
In the following example, we are concatenating the strings with the specified delimiter.
public class StringJoinExample {
public static void main(String[] args) {
// Here , is a delimiter and elements are strings
String result = String.join(", ", "Cricket", "Hockey", "Tennis");
System.out.println(result); // Output: "Cricket, Hockey, Tennis"
}
}
2. Joining Elements of a List (Collection)
import java.util.Arrays;
import java.util.List;
public class StringJoinExample {
public static void main(String[] args) {
List<String> sports = Arrays.asList("Cricket", "Hockey", "Tennis");
// Here, we are joining elements of an ArrayList with
// comma as delimiter
String result = String.join(", ", sports);
System.out.println(result); // Output: "Cricket", "Hockey", "Tennis"
}
}
3. Joining Varargs of Strings
In the following example, we are using String.join()
method with a variable number of string arguments. Refer: Java varargs Tutorial
public class StringJoinExample {
public static void main(String[] args) {
String result = String.join(" | ", "Java", "Python", "C++", "JavaScript");
System.out.println(result); // Output: "Java | Python | C++ | JavaScript"
}
}
4. Joining Elements of a Collection
Here, we are using String.join()
method to concatenate the elements of a HashSet.
import java.util.HashSet;
public class StringJoinHashSetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");
fruits.add("date");
// Joining the elements of HashSet with comma as delimiter
String result = String.join(", ", fruits);
// Output: "banana, cherry, apple, date"
// (order can be different)
System.out.println(result);
}
}
Practical Uses of String join() method
- CSV Generation: This method can be used to join elements with a comma to generate CSV records.
- Logging: Concatenating multiple values with a separator for logging purposes.
Leave a Reply