File: ModifySourceCollectionInStream.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (28 lines) | stat: -rw-r--r-- 1,039 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
From the javadoc for
[`java.util.stream: Non-interference`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/package-summary.html#NonInterference):

> Accordingly, behavioral parameters in stream pipelines whose source might not
> be concurrent should never modify the stream's data source. A behavioral
> parameter is said to interfere with a non-concurrent data source if it
> modifies, or causes to be modified, the stream's data source. The need for
> non-interference applies to all pipelines, not just parallel ones. Unless the
> stream source is concurrent, modifying a stream's data source during execution
> hg of a stream pipeline can cause exceptions, incorrect answers, or
> nonconformant behavior.

That is, prefer this:

```java
mutableValues.stream()
  .filter(x -> x < 5)
  .collect(Collectors.toList()) // Terminate stream before source modification.
  .forEach(mutableValues::remove);
```

to this:

```java
mutableValues.stream()
  .filter(x -> x < 5)
  .forEach(mutableValues::remove);
```