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) {
            doSomething();
        }
    }

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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
scroll top