Java External & Internal Iterators
Streams and Lambdas
Java introduces internal iterators with streams.
Let’s say we need to get even number count of a given list.
List<Integer> numbers= Arrays.asList(1,2,3,4,5,6,7,8,9,10);We will use mod to filter the numbers from the list. If it’s zero it’s even if not it’s odd.
Number % 2 == 0Now let’s get the count using traditional for loop.
for(int i=0; i<numbers.size();i++)
if(numbers.get(i)%2==0)
result++;Now let’s do it with anoteher for loop.
for(int e:numbers)
if(e % 2 == 0)
result++;Both above looping methods are classified as external iterators as it requires us to maintain how to do the iteration. We will pick the number one by one and then find the even numbers.
Internal Iterator
Let’s try to do the same with an internal iterator. This is done using streams feature of the Java version.
result = numbers.stream()
.filter(new Predicate<Integer>() {
@Override
public boolean test(Integer e) {
return e % 2 == 0;
}
})
.count();If we add lambdas in to this implementation will be more simpler.
result = numbers.stream()
.filter(e -> e % 2 == 0)
.count();If you have a closer look you will see we aren’t doing the iteration here. Iteration is handled by Java itself.
Comparison
Traditional iteration using for loop is external and looping using streams is internal. When we compare both of these approaches internal iterators are very easy of using and we don’t need to know maintain the things such as item type, length of the list and etc. With the internal iterators we just simply can focus on business logic and the rest can be handed over to framework. On the other side external iterators gives more control over looping. So it’s up to you when to use what.
Get Nuwan Zen’s stories in your inbox
Join Medium for free to get updates from this writer.
Happy coding …
Read my other blogs:







