Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 stream interference versus non-interference

I understand why the following code is ok. Because the collection is being modified before calling the terminal operation.

List<String> wordList = ...;
Stream<String> words = wordList.stream();
wordList.add("END"); // Ok
long n = words.distinct().count();

But why is this code is not ok?

Stream<String> words = wordList.stream();
words.forEach(s -> if (s.length() < 12) wordList.remove(s)); // Error—interference
like image 952
Aravind Yarram Avatar asked Jul 19 '14 15:07

Aravind Yarram


People also ask

Does Java 8 stream improve performance?

In Java8 Streams, performance is achieved by parallelism, laziness, and using short-circuit operations, but there is a downside as well, and we need to be very cautious while choosing Streams, as it may degrade the performance of your application.

What are two types of streams in Java 8?

With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.

What is the advantage of stream in Java 8?

There are a lot of benefits to using streams in Java, such as the ability to write functions at a more abstract level which can reduce code bugs, compact functions into fewer and more readable lines of code, and the ease they offer for parallelization.


1 Answers

Stream.forEach() is a terminal operation, and the underlying wordList collection is modified after the terminal has been started/called.

like image 175
Joachim Isaksson Avatar answered Sep 19 '22 10:09

Joachim Isaksson