# Use String Join

# Description

Java 8 introduced String.join which is a convenient method for concatenating String values of Iterables. 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

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID UseStringJoin
First seen in jSparrow version 3.15.0
Minimum Java version 8
Remediation cost 5 min