Skip to main content

Java 8: Rewrite For-loops using Stream API

Java 8 Tip: Anytime you write a Java For-loop, ask yourself if you can rewrite it with the Streams API.

Now that I have moved to Java 8 in my work and home development, whenever I want to use a For-loop, I write it and then see if I can rewrite it using the Stream API.

For example: I have an object called myThing, some Collection-like data structure which contains an arbitrary number of Fields. Something has happened, and I want to set all of the fields to some common state, in my case "Hidden"


From long habit, I immediately think of doing this in a for-loop, something like this:

for ( int i = 1; i <= myThing.size(); i++)
   myThing.getField(i).setHidden(true);

For-loops have their advantages:

  • they are flexible in start, end, and increment values; 
  • they can be arbitrarily long and complex; 
  • they are well-understood from years of hands-on experience; 
  • the looping-value can be reused throughout the loop; etc.

But they have their idiosyncrasies, too. Things like:

  • is my underlying collection zero-based or one-based? 
  • do I need less-than-or-equals or just less-than? etc.

Now with Java 8, I can rewrite the above for-loop as the following:

myThing.stream().forEach(field -> field.setHidden(true));

Isn't that sweet? One line, with less mathematical expression and more natural-language expression. This short little snippet much more clear and expressive, with none of the bounds-questions that arise with the old for-loop. Much less thinking required, too, to parse its meaning and understand what is going on.