# Use String Join

# Properties

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

# 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() with concatenations using String.join(). A performance improvement can be observed with the increase of the number of elements in the Iterable.

# Benefits

Improves performance and reduces code clutter.

# 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

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊