Java8: Lambdas & Internal Iterators

Nuwan Zen
1 min readMar 9, 2021

Java8 introduced a new type of iterator called internal iterators.

External iterators are

for(int i=0;i<list.size();i++){

and

for(Person p:list)

Below is an example for a Internal iterator introduced in Java 8. Let’s see how can we iterate a Person object list.

class Person{
String name;
int age;
Person(String name, int age){
this.age=age;
this.name=name;
}
@Override
public String toString(){
return name +"'s age is " + age;
}
}

We will create a list of objects and iterate.

List<Person> list= Arrays.asList(
new Person("nuwan",20),
new Person("sen",30)
);
list.forEach(System.out::println);

With a single line of code we can print whole list.

list.forEach(System.out::println);

This line accepts get the objects in the list and print. In-order to have a readable out put we may have to override the toString method of the Person class as these lambdas work with single arguments only.

As in this forEach implementation we aren’t controlling the execution unlike external iterators it can help parallel processioning heavily.

Ref: https://youtu.be/tfbmYBcq5CM

Read my other blogs:

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!