IntelliJ IDEA recommended to me just now to replace the following for-each loop with a Java 8 "forEach" call:

    for (Object o : objects) {
        if (o instanceof SomeObject) {

The recommended call would like like this:

objects.stream().filter(o -> o instanceof SomeObject).forEach(o -> doSomething());

Unless I'm misunderstanding how the underlying functionality of Stream works, it seems to me like using stream is an O(2n) operation as opposed to an O(n) operation for the standard for-each loop.

  • 8
    Why do you think it's O^2? In fact, streams were invented specifically to (a) allow nicer syntax and (b) not introduce extra overhead. (In fact, they often reduce overhead via lazy evaluation.) May 7, 2015 at 13:40
  • Just based on the syntax, it looks like it's first iterating to filter and then iterating over the filtered objects a second time to run my code.
    – Mirrana
    May 7, 2015 at 13:45
  • 6
    Even if it did that that would still be O(2*N), which is O(N), i.e. linear and not quadratic. But actually the iterations are interleaved with each other, and both may terminate early if the result is already known - that's the beauty of streams. It's definitely worth spending 15 minutes to read up on the streams in Java 8; as Venkat Subramaniam writes, ''Lambda expressions are the gateway drug to Java 8, but Streams are the real addiction.'' May 7, 2015 at 13:52
  • 1
    Besides: your loop is an antipattern ;) May 7, 2015 at 14:06
  • 1
    @ThomasJunk Can you explain how it's an antipattern? I'm not familiar with this one.
    – Mirrana
    May 7, 2015 at 14:56

1 Answer 1


Java streams do not iterate through your collection once for each statement, despite what the syntax implies. It applies the entire chain to each element, one element at a time.

In your case, the stream would operate exactly like the loop. Take an element, check it against your predicate, and then apply your operation, then move on to the next element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.