Java 8-Internal vs. External Iteration
In this post we will understand the Java 8-Internal vs. External Iteration statement using simple example.
Video
This tutorial is explained in the below Youtube Video.- External Iterators- This Iterator is also known as active iterator or explicit iterator. For this type of iterator
the control over iteration of elements is with the programmer. Which means that the programmer define when and how
the next element of iteration is called.
List<String> items = new ArrayList<>(); items.add("test1"); items.add("test2"); items.add("test3"); items.add("test4"); items.add("test5"); //Traditional java for-each iterator which is an External Iterator. for (String item : items) { System.out.println(item); }
Map<String, String> map = new HashMap<>(); map.put("1", "test1"); map.put("2", "test2"); map.put("3", "test3"); map.put("4", "test4"); map.put("5", "test5"); map.put("6", "test6"); //Traditional way of iterating map elements using external iterator. for(Map.Entry<String, String> entry :map.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); }
- Internal Iterators- This Iterator is also known as passive iterator, implicit iterator or callback iterator. For this type of
iterator the control over the iteration of elements lies with the iterator itself. The programmer only tells the iterator
"What operation is to be performed on the elements of the collection". Thus the programmer only declares what is to be done
and does not manage and control how the iteration of individual elements take place.
List<String> items = new ArrayList<>(); items.add("test1"); items.add("test2"); items.add("test3"); items.add("test4"); items.add("test5"); //iterate over list items //Java 8 forEach iterator which is an Internal Iterator. items.forEach(item -> System.out.println(item));
Map<String, String> map = new HashMap<>(); map.put("1", "test1"); map.put("2", "test2"); map.put("3", "test3"); map.put("4", "test4"); map.put("5", "test5"); map.put("6", "test6"); //iterate over map items //Java 8 forEach iterator which is an Internal Iterator. map.forEach((key,value)->{ System.out.println(key); System.out.println(value); });
See Also
Java - PermGen space vs MetaSpace Understand Java 8 Method References using Simple Example Java 8 Lambda Expression- Hello World Example Understanding Java 8 Streams using examples. Understanding Java 8 Optional using examples.