# Use String Join
# Description
Java 8 introduced String.join which is a convenient method for concatenating String values of Iterable
s.
This rule replaces String concatenations performed using Collectors.joining()
(opens new window) with concatenations using String.join()
(opens new window).
A performance improvement can be observed with the increase of the number of elements in the Iterable.
# Benefits
Improves performance and reduces code clutter.
# Tags
# Code Changes
# Concatenating without delimiter
Pre
String result = values.stream().collect(Collectors.joining());
Post
String result = String.join("", values);
# Concatenating with delimiter
Pre
String result = values.stream().collect(Collectors.joining(","));
Post
String result = String.join(",", values);
# Using static imports
Pre
String result = values.stream().collect(joining(","));
Post
String result = String.join(",", values);
# Bytecode JDK 1.8
Pre
public void original(List<String> values) {
String result = values.stream().collect(Collectors.joining(","));
}
0 aload_1
1 invokeinterface #2 <java/util/List.stream> count 1
6 ldc #3 <,>
8 invokestatic #4 <java/util/stream/Collectors.joining>
11 invokeinterface #5 <java/util/stream/Stream.collect> count 2
16 checkcast #6 <java/lang/String>
19 astore_2
20 return
Post
public void transformed(List<String> values) {
String result = String.join(",", values);
}
0 ldc #3 <,>
2 aload_1
3 invokestatic #7 <java/lang/String.join>
6 astore_2
7 return
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.
# Properties
Property | Value |
---|---|
Rule ID | UseStringJoin |
First seen in jSparrow version | 3.15.0 |
Minimum Java version | 8 |
Remediation cost | 5 min |