You can do it like this:

IntStream.range(0, numbers.length)
  .forEach(index -> {
    doubleNumbers[index] = numbers[index] * 2;
    tripleNumbers[index] = numbers[index] * 3;
  });
Answer from thegauravmahawar on Stack Overflow
🌐
Reddit
reddit.com › r/learnjava › using for loops vs streams - which method is preferred and why?
r/learnjava on Reddit: Using for loops vs streams - which method is preferred and why?
May 18, 2024 -

I'm currently learning Java (a mixture of Mooc.Fi course and some stuff on Youtube/Udemy) and I just recently was introduced to functional programming and streams in particular.

I'll be honest in that I'm not really sure in what cases I would use a for loop vs a stream and why.

Can anybody help me out in regards to knowing when I would use a for-loop vs a stream? Thanks!

Discussions

foreach - How do I iterate over a stream in Java using for? - Stack Overflow
This can be considered as bad design from the Java-8 point of view, but it's still the code which works and should be supported. Refactoring everything at once might be problematic. I personally saw many for loops which may benefit from stream API, but cannot be easily converted to forEach/collect. More on stackoverflow.com
🌐 stackoverflow.com
In Java, what are the advantages of streams over loops? - Stack Overflow
Syntactic fun aside, Streams are ... every Java SE class which implements Iterable are entirely in memory. A disadvantage of a Stream is that filters, mappings, etc., cannot throw checked exceptions. This makes a Stream a poor choice for, say, intermediate I/O operations. ... Of course, you can loop over infinite sources too. 2017-05-25T14:38:04.237Z+00:00 ... But if the elements to process are persisted in a DB, how do you use ... More on stackoverflow.com
🌐 stackoverflow.com
Java 8 nested loops to stream - Stack Overflow
Trying to get my head round the Java 8 streams syntax with a simple example. Had a look at the other similar questions on this topic, but could not find any solutions that would match my example and would work for me. Basically I am trying to refactor the following snippet with two nested loops to use ... More on stackoverflow.com
🌐 stackoverflow.com
Java Stream drastically increases execution time compared to for loop
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
23
19
November 3, 2024
🌐
Baeldung
baeldung.com › home › java › java streams › streams vs. loops in java
Streams vs. Loops in Java | Baeldung
January 8, 2024 - Streams, introduced in Java 8, offer a functional and declarative approach, while for-loops provide a traditional imperative method. By the end of the article, we can make the most suitable decision for our programming tasks.
🌐
Stackify
stackify.com › streams-guide-java-8
A Guide to Java Streams: In-Depth Tutorial With Examples
September 4, 2024 - Let’s now see some common usages ... support in the language. forEach() is the simplest and most common operation; it loops over the stream elements, calling the supplied function on each element....
🌐
Medium
medium.com › @ezzeddinebilel › java-stream-and-for-loop-a-balanced-view-on-performance-a38e45f271e5
Java Stream and For Loop: A Balanced View on Performance | by Bilel Ezzeddine | Medium
February 18, 2024 - In this article, we delve into the performance considerations of Streams compared to traditional for loops in Java. Additionally, we explore algorithmic complexity to uncover insights into their efficiency across different scenarios.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparing-streams-to-loops-in-java
Comparing Streams to Loops in Java - GeeksforGeeks
October 20, 2022 - Terminal operations such as forEach, collect, or reduce are either void or return a non-stream result. Streams bring functional programming in Java and are supported starting in Java 8. The Java 8 stream is an implementation of the PQSA1 Pipes and Filter pattern. ... // Java Program to Compare Streams to Loops // Importing required libraries import java.io.IOException; import java.lang.String; import java.nio.file.*; import java.util.*; import java.util.Arrays; import java.util.List; import java.util.stream.*; // Main class // JavaStreams class GFG { // Main driver method public static void main(String[] args) throws IOException { // 1.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream foreach()
Java Stream forEach() with Examples - HowToDoInJava
March 14, 2022 - List<Integer> list = Arrays.asList(2, ... output. 10 8 6 4 2 · In this tutorial, we learned to use the forEach() method to iterate through all the elements of a Stream....
Find elsewhere
🌐
JDriven Blog
blog.jdriven.com › 2019 › 10 › loop
Java streams vs for loop - JDriven Blog
November 14, 2019 - The short version basically is, if you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead.
🌐
Jsparrow
jsparrow.github.io › rules › enhanced-for-loop-to-stream-for-each.html
Replace For-Loop with Iterable::forEach | jSparrow Documentation
Use Stream::collect · Use SecureRandom · Use String Join · Use String Literals · Use StringBuilder::append · Use StringUtils Methods · Use Switch Expression · Use Ternary Operator · Use Text Block · Use Try-With-Resource · This rule replaces enhanced for loops (for-each-loops) with an invocation of java.lang.Iterable::forEach-method and passes the body of the for-loop as a lambda Consumer parameter.
🌐
Jsparrow
jsparrow.github.io › rules › enhanced-for-loop-to-stream-take-while.html
Replace For-Loop with Stream::takeWhile | jSparrow Documentation
Map<Integer, User> users = findAllSorted(); users.entrySet() .stream() .takeWhile(entry -> isEarlyCustomerId(entry.getKey())) .forEach(entry -> { User user = entry.getValue(); attachDiscount(user); }); You can auto-refactor this with jSparrow. Drop this button to your Eclipse IDE workspace to install jSparrow for free: Need help? Check out our installation guide. ← Replace For-Loop with Stream::findFirst Replace Inefficient Constructors with valueOf() →
🌐
TutorialsPoint
tutorialspoint.com › how-to-iterate-list-using-streams-in-java
How to iterate List Using Streams in Java?
June 6, 2025 - We use the stream() method to create a sequential stream from the current list and use forEach() method with lambda expression (->) to iterate over it: import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class iterateList { public static void main(String[] ...
Top answer
1 of 5
421

Interesting that the interview question asks about the advantages, without asking about disadvantages, for there are are both.

Streams are a more declarative style. Or a more expressive style. It may be considered better to declare your intent in code, than to describe how it's done:

 return people
     .filter( p -> p.age() < 19)
     .collect(toList());

... says quite clearly that you're filtering matching elements from a list, whereas:

 List<Person> filtered = new ArrayList<>();
 for(Person p : people) {
     if(p.age() < 19) {
         filtered.add(p);
     }
 }
 return filtered;

Says "I'm doing a loop". The purpose of the loop is buried deeper in the logic.

Streams are often terser. The same example shows this. Terser isn't always better, but if you can be terse and expressive at the same time, so much the better.

Streams have a strong affinity with functions. Java 8 introduces lambdas and functional interfaces, which opens a whole toybox of powerful techniques. Streams provide the most convenient and natural way to apply functions to sequences of objects.

Streams encourage less mutability. This is sort of related to the functional programming aspect -- the kind of programs you write using streams tend to be the kind of programs where you don't modify objects.

Streams encourage looser coupling. Your stream-handling code doesn't need to know the source of the stream, or its eventual terminating method.

Streams can succinctly express quite sophisticated behaviour. For example:

 stream.filter(myfilter).findFirst();

Might look at first glance as if it filters the whole stream, then returns the first element. But in fact findFirst() drives the whole operation, so it efficiently stops after finding one item.

Streams provide scope for future efficiency gains. Some people have benchmarked and found that single-threaded streams from in-memory Lists or arrays can be slower than the equivalent loop. This is plausible because there are more objects and overheads in play.

But streams scale. As well as Java's built-in support for parallel stream operations, there are a few libraries for distributed map-reduce using Streams as the API, because the model fits.

Disadvantages?

Performance: A for loop through an array is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse.

Familiarity.The world is full of experienced procedural programmers, from many language backgrounds, for whom loops are familiar and streams are novel. In some environments, you want to write code that's familiar to that kind of person.

Cognitive overhead. Because of its declarative nature, and increased abstraction from what's happening underneath, you may need to build a new mental model of how code relates to execution. Actually you only need to do this when things go wrong, or if you need to deeply analyse performance or subtle bugs. When it "just works", it just works.

Debuggers are improving, but even now, when you're stepping through stream code in a debugger, it can be harder work than the equivalent loop, because a simple loop is very close to the variables and code locations that a traditional debugger works with.

2 of 5
36

Syntactic fun aside, Streams are designed to work with potentially infinitely large data sets, whereas arrays, Collections, and nearly every Java SE class which implements Iterable are entirely in memory.

A disadvantage of a Stream is that filters, mappings, etc., cannot throw checked exceptions. This makes a Stream a poor choice for, say, intermediate I/O operations.

🌐
Mkyong
mkyong.com › home › java8 › java 8 stream.iterate examples
Java 8 Stream.iterate examples - Mkyong.com
November 29, 2018 - In Java 8, we can use Stream.iterate to create stream values on demand, so called infinite stream. ... //Stream.iterate(initial value, next value) Stream.iterate(0, n -> n + 1) .limit(10) .forEach(x -> System.out.println(x));
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - Where loops provide the break keyword, we have do something a little different to stop a Stream. ... The article is an example-heavy introduction of the possibilities and operations offered by the Java 8 Stream API. ... In Java, the Collection interface has Iterable as its super interface. This interface has a new API starting with Java 8: ... Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”
🌐
Medium
medium.com › @katerinaCodes › for-loops-vs-java-streams-d5456bc3f1ad
For Loops vs Java Streams. My first programming language was Ruby… | by Katerina | Medium
July 19, 2022 - In Java, there are no Enumerable methods but the operations that you can use on streams provide similar functionality. To use the stream operations you have to convert your array to a stream.
🌐
Better Programming
betterprogramming.pub › dont-use-java-for-loops-consider-java-streams-instead-e439d09940b7
Don’t Use Java For Loops — Consider Java Streams Instead | by Jordan Williams | Better Programming
June 4, 2021 - We can create streams or transform existing structures into streams. Streams can be a replacement for looping because they allow for the processing of a sequence of data (similarly to a loop).
🌐
javathinking
javathinking.com › blog › java-convert-for-loop-to-stream
Java: Convert For Loop to Stream — javathinking.com
This blog post will guide you through the process of converting traditional for loops to streams, explaining core concepts, typical usage scenarios, common pitfalls, and best practices. ... A stream in Java is a sequence of elements supporting various sequential and parallel aggregate operations.