table of Contents
StringUtils.join() implementation
Comparison of two implementation methods
You may have encountered the need to concatenate arrays or collections into a new string with certain ",", "-", "." and other concatenated characters. The concatenated string will be like this a, b, c or abc Or abc etc.
You may want to traverse the splicing and remove the last spliced character.
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList(new String[]{"a", "b", "c"}));
StringBuilder stringBuilder = new StringBuilder();
for (String s : list) {
stringBuilder.append(s + ",");
}
System.out.println(stringBuilder.substring(0, stringBuilder.length() - 1));
}
Or think about traversing first and processing the last element of the array separately.
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList(new String[]{"a", "b", "c"}));
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.size() -1 ;i ++) {
stringBuilder.append(list.get(i) + ",");
}
System.out.println(stringBuilder.append(list.get(list.size() - 1)).toString());
}
The above two methods either process the last spliced special character, or need to process the last character separately, neither is particularly elegant, so is there an elegant way to implement this piece? Not to mention, there are really two ways to do it.
StringUtils.join() implementation
pom dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
api description
Code
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList(new String[]{"a", "b", "c"}));
System.out.println(StringUtils.join(list, ","));
}
String.join() implementation
pom dependency
String.join() is a new method of JDK8, and no external dependencies are required.
api description
Code
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList(new String[]{"a", "b", "c"}));
System.out.println(String.join(",", list));
}
StringUtils.join and String.join() are both done in one line of code. Isn't it elegant?
Comparison of two implementation methods
Parameter order : StringUtils.join() The first parameter is an array or collection, and the second parameter is a concatenation character; the first parameter of String.join() is a concatenation character, and the second parameter is an array or collection.
Parameter range : StringUtils.join() can be passed Integer or other types of collections or arrays; String.join() can only be passed in collections or arrays that implement the charSequence interface type.
Comparison and summary : If it is a collection or array of string type, String.join() is recommended, and StringUtils.join() is recommended for other types.