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)