rspec/rules/S3958/java/rule.adoc

29 lines
1.1 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
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
----
widgets.stream().filter(b -> b.getColor() == RED); // Noncompliant
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
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();
----
2021-04-28 16:49:39 +02:00
== See
* https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps[Stream Operations]