# Use Arrays Stream

# Description

This rule transforms Arrays.asList(T..values).stream() into either of the following:

Arrays.asList(1, 2, 3).stream()

is transformed to:

Arrays.stream(new int[]{1, 2, 3})

Thus, avoiding an unnecessary boxing of the elements of the stream.

Arrays.asList("1", "2", "3").stream()

is transformed to:

Stream.of("1", "2", "3")

# Benefits

Improves performance by avoiding unnecessary boxing of stream elements. Improves readability by using short hand method Stream.of(T... values) (opens new window) for generating a stream.

# Tags

# Code Changes

# Avoid Boxing of IntStream

Pre

Arrays.asList(1, 2, 3).stream()
    .forEach(value -> consumePrimitiveInt(value));

Post

Arrays.stream(new int[] { 1, 2, 3})
    .forEach(value -> consumePrimitiveInt(value));

# Using Stream.of

Pre

Arrays.asList("1", "2", "3").stream()
    .forEach(value -> consumeString(value));

Post

Stream.of("1", "2", "3")
    .forEach(value -> consumeString(value));

# Existing String Array to Stream

Pre

String [] stringArray = stringArrayFactory();
Arrays.asList(stringArray).stream()
    .forEach(value -> consumeString(value));

Post

String [] stringArray = stringArrayFactory();
Stream.of(stringArray)
    .forEach(value -> consumeString(value));

🛠️ 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 UseArraysStream
First seen in jSparrow version 3.18.0
Minimum Java version 8
Remediation cost 5 min
Links