Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Java 8 Iterable.forEach() vs foreach loop

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 734
    Comment on it

    foreach loop

    In Jdk 1.5 generics concept can be introduced and do some enhancement in for loop and the enhanced for-loop is introduced. The enhanced for-loop is reduce the overhead to print the values of the arrays and collections because it works on values . To reduce the overhead of iterations using iterator and calls to its hasNext() and next() methods. We need not to call hasNext() and next() methods explicitly in the code.

    List<String> names = new LinkedList<String>();
    
    for (String name : names)
        System.out.println(name);
    

    forEach loop

    In Jdk 1.8 the forEach method is introduced and use for an active iterator for Collection(list, set, map) classes. We can also iterate our collection classes using this method. This method takes a single parameter that is functional interface. The below code will show you how to use forEach() method.

    List<String> names = new ArrayList<>();
    
    names.forEach(name -> System.out.println(name));
        or
    names.forEach(name -> {    System.out.println(name)    });
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: