For loop in Java 8

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 :


        // Classic for loop
        for(int i=0;i<5;i++){




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 :


        List categories = Arrays.asList("Java","Dot Net","Oracle","Excel");
  // For Each loop

  for(String category: categories){




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 :


        // Java 8 Lambda For loop> System.out.println(category));


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


package com.topjavatutorial.java8examples;

import java.util.Arrays;
import java.util.List;

public class ForLoopExample {

  public static void main(String[] args) {
    List categories = Arrays.asList("Java","Dot Net","Oracle","Excel");
    // Classic for loop
    for(int i=0;i<categories.size();i++){ System.out.println(categories.get(i)); } 

                // For Each loop 

                for(String category: categories){ System.out.println(category); } 

                // Java 8 Lambda For loop 

      > System.out.println(category));



You may like the following articles on Java 8:




© 2015 – 2016, https:. All rights reserved. On republishing this post, you must provide link to original post


    int n=10;
    int i;
    int j;
    int k;

  2. Please help me out in this
    2 6
    3 7 10
    4 8 11 13
    5 9 12 14 15

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: