Java streams provide a declarative pipeline: a source, zero or more intermediate operations (filter, map, sorted, distinct) and one terminal operation (collect, forEach, reduce, findFirst, count). Lazy evaluation - Intermediate operations do nothing until a terminal operation is invoked. - Elements flow through the pipeline one at a time (vertical processing), not stage by stage. - Short-circuiting operations (findFirst, anyMatch, limit) stop early: Optional<Order> firstLarge = orders.stream() .filter(o -> o.total().compareTo(LIMIT) > 0) // stops at the first match .findFirst(); - This allows working with infinite streams: Stream.iterate(1, n -> n + 1).filter(this::isPrime).limit(10).toList(). - A stream can be consumed only once. - Stateful operations such as sorted() and distinct() must buffer data, so they lose some of the laziness benefits. Cases where a normal loop is clearer - Complex control flow: early returns, break or continue with conditions, or multiple outputs from one pass. - Checked exceptions: lambdas cannot throw checked exceptions without wrapping, which makes stream code awkward. - Mutating local state or several variables at once (streams discourage side effects). - Index-based logic (comparing an element with the previous one). - Debugging: stepping through a loop is often easier than through a lambda pipeline. Cases where a loop can be faster - Small collections in hot paths: stream setup (objects, lambdas) adds overhead. - Primitive work where boxing occurs: Stream<Integer> boxes values. Use IntStream, LongStream or DoubleStream, or a plain loop over an int[]. - Very simple operations (summing an array) where a for loop has no allocations and is easily optimised by the JIT. Parallel streams - parallelStream() uses the common ForkJoinPool. It helps only for large, CPU-bound, independent work with splittable sources (ArrayList, arrays), and can hurt for small data, I/O or shared mutable state. Rule of thumb: use streams for clear transformations (filter, map, group, collect), use loops for complex logic or measured hot spots, and benchmark with JMH rather than guessing.
Ravindra Wadile · · 0 likes