The String.join()
method in Java is a static method added in Java 8 to the java.lang.String
class. The String.join()
is a static utility method used to concatenate multiple strings, arrays or collections (like lists and sets) of strings. This method makes it easier to join multiple strings with a specific delimiter. A delimiter is a sequence of characters used to separate strings.
This method returns a new String
composed of copies of the CharSequence
elements joined together with a copy of the specified delimiter. This method saves us from writing boilerplate loop code just for concatenating strings with a delimiter.
Here is an example of how you can use it:
package org.kodejava.lang;
import java.util.Arrays;
import java.util.List;
public class StringJoinList {
public static void main(String[] args) {
List<String> list = Arrays.asList("Java", "is", "cool");
String result = String.join(" ", list);
System.out.println(result);
}
}
Output:
Java is cool
In this example, String.join()
takes two parameters:
- A
delimiter
that is aCharSequence
(like a String) that is placed between each joined String. - An
Iterable
object like aList
or aSet
, over which the method iterates and joins all elements into a single String.
You can also use String.join()
with an array of elements:
package org.kodejava.lang;
public class StringJoinArray {
public static void main(String[] args) {
String[] array = new String[]{"Java", "is", "cool"};
String result = String.join(" ", array);
System.out.println(result);
}
}
Output:
Java is cool
In this case, String.join()
still takes a delimiter
as the first argument, but the second argument is an Array
of elements to be joined.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024