Core JavaJava 8

Java 8 for loop

For loop in Java has changed a lot from the way it first appeared in jdk 1.


Here is an example of the classical for loop :



Java 5 added the forEach loop that made looping with collections easier as it removed declaration of the looping variable and checking length of the collection.


Here is an example of the forEach loop :



Java 8 added lambda expressions and Stream api.


The Stream api java.util.Stream provides a forEach that can be used to loop over collection as shown below :



Here is the complete example that loops over a list using different for loops :



You may like the following articles on Java 8:




© 2015, All rights reserved.