String.join和StringUtils.join
1. StringUtils.join()
list集合
public static String join(List<?> list,
String separator,
int startIndex,
int endIndex)
Joins the elements of the provided List
into a single String containing the provided list of elements.
No delimiter is added before or after the list. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null, *) = null
StringUtils.join([], *) = ""
StringUtils.join([null], *) = ""
StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
StringUtils.join(["a", "b", "c"], null) = "abc"
StringUtils.join([null, "", "a"], ';') = ";;a"
-
Parameters:
list
- theList
of values to join together, may be nullseparator
- the separator character to usestartIndex
- the first index to start joining from. It is an error to pass in a start index past the end of the listendIndex
- the index to stop joining from (exclusive). It is an error to pass in an end index past the end of the list -
Returns:
the joined String,
null
if null list input -
Since:
3.8
数组
public static String join(char[] array,
char delimiter)
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null, *) = null
StringUtils.join([], *) = ""
StringUtils.join([null], *) = ""
StringUtils.join([1, 2, 3], ';') = "1;2;3"
StringUtils.join([1, 2, 3], null) = "123"
-
Parameters:
array
- the array of values to join together, may be nulldelimiter
- the separator character to use -
Returns:
the joined String,
null
if null array input -
Since:
3.2
2. String.join()
Join array or list of strings
String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
This method is used to join array of strings or list of strings.
Java program to join list of strings
List<String> strList = Arrays.asList("How", "To", "Do", "In", "Java");
String joinedString = String.join(", ", strList);
System.out.println(joinedString);
Output:
How, To, Do, In, Java
Java program to join array of strings
String[] strArray = { "How", "To", "Do", "In", "Java" };
String joinedString = String.join(", ", strArray);
System.out.println(joinedString);
Output:
How, To, Do, In, Java