rspec/rules/S3958/java/rule.adoc

50 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
There are two types of stream operations: intermediate operations, which return another stream, and terminal operations, which return something other than a stream. Intermediate operations are lazy, meaning they aren't actually executed until and unless a terminal stream operation is performed on their results. Consequently, if the result of an intermediate stream operation is not fed to a terminal operation, it serves no purpose, which is almost certainly an error.
2021-04-28 16:49:39 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
widgets.stream().filter(b -> b.getColor() == RED); // Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
int sum = widgets.stream()
.filter(b -> b.getColor() == RED)
.mapToInt(b -> b.getWeight())
.sum();
Stream<Widget> pipeline = widgets.stream()
.filter(b -> b.getColor() == GREEN)
.mapToInt(b -> b.getWeight());
sum = pipeline.sum();
----
== Resources
2021-04-28 16:49:39 +02:00
* https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps[Stream Operations]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Refactor the code so this stream pipeline is used.
=== Highlighting
The intermediate stream function call
endif::env-github,rspecator-view[]