Iterator

Iterable Java Example – java.lang.Iterable Interface

This article shows an Iterable Java example – java.lang.Iterable interface. This is defined in java.lang package and was introduced with Java 5. The Iterable is defined as a generic type; Iterable<T>, where T type parameter represents the type of elements returned by the iterator.

An object that implements this interface allows it to be the target of the “foreach” statement. The for-each loop is used for iterating over arrays, collections etc. Collection classes and classes where iterations are useful implement this interface.

Before the iterable’s for-each loop was introduced, a way to iterate is to use the for(;;) loop or to use an Iterator; typically the Iterator could be acquired by invoking a collection object’s iterator() method. The iterator has been in Java since Java 1.2.

The Iterable interface provides a clean approach to coding the iteration functionality. An example shows iterating over a List collection with String object elements:

1
2
3
4
List<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
1
2
3
4
for (String s : stringList) {
 
    System.out.println(s);
}

The above for-each code is much cleaner and elegant than the following two code snippets which have the same functionality. The following code use the for(;;) loop and the Iterator respectively.

1
2
3
4
for (int i = 0; i < stringList.size(); i++) {
 
    System.out.println(stringList [i]);
}
1
2
3
4
5
6
Iterator<String> iter = stringList.iterator();
 
while (iter.hasNext()) {
 
    System.out.println(iter.next());
}

Note that there is also a possibility of introducing a bug in the above two code snippets, because of the details.

1. Iterable Java Example

The following example class implements the Iterable interface. The class takes an input array of any type and iterates it in a for-each loop and in reverse order.

The Iterable interface has one method to override: Iterator<T> iterator().

The example has the iterable implementation MyIterable.java and a tester class MyIterableTester.java. The example code requires Java SE 5 or greater.

MyIterable Class example is shown in the code below:

MyIterable

import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collections;
 
public class MyIterable implements Iterable {
 
    private List list;
 
    public MyIterable(T [] t) {
 
        list = Arrays.asList(t);
        Collections.reverse(list);
    }
 
    @Override
    public Iterator iterator() {
 
        return list.iterator();
    }
}

MyIterableTester Class example is shown in the code below:

import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collections;
 
class MyIterable<T> implements Iterable<T> {
 
    private List<T> list;
 
    public MyIterable(T [] t) {
 
        list = Arrays.asList(t);
        Collections.reverse(list);
    }
 
    @Override
    public Iterator<T> iterator() {
 
        return list.iterator();
    }
}
public class MyIterableTester {
 
    public static void main(String [] args) {
 
        Integer [] ints = {1, 2, 3};
 
        MyIterable<Integer> myList = new MyIterable<>(ints);
 
        for (Integer i : myList) {
 
            System.out.println(i);
        }
    }
}

The code above when executed will output as:

MyIterableTester

3
2
1

2. Custom Iterable Data Structure

Let us look at building a custom iterable data structure. First, we will look at Employee Class. The Employee class has attributes firstName,lastName, and employeeId. The Employee class code is implemented as below:

Employee Class

import static java.lang.String.format;
import java.util.*;

public class Employee {
   private String firstName, lastName;
   private int employeeId;
   public Employee(){ }
   public Employee(String firstName, String lastName, int employeeId) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.employeeId = employeeId;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getEmployeeId() {
      return employeeId;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
   }
   @Override
   public String toString() {
      return format("First Name: %s Last Name: %s EmployeeId: %d", firstName, lastName, employeeId);
   }
}

Now let us look at EmployeeArrayList implementation which implements the Iterator interface. The iterator method is overridden to return the employees arrayList iterator.

import static java.lang.String.format;
import java.util.*;

class Employee {
   private String firstName, lastName;
   private int employeeId;
   public Employee(){ }
   public Employee(String firstName, String lastName, int employeeId) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.employeeId = employeeId;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getEmployeeId() {
      return employeeId;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
   }
   @Override
   public String toString() {
      return format("First Name: %s Last Name: %s EmployeeId: %d", firstName, lastName, employeeId);
   }
}

class EmployeeArrayList implements Iterable<Employee> {
   private List<Employee> employees;
  
   public EmployeeArrayList() {
      employees = new ArrayList<Employee>();
   }
   public EmployeeArrayList(int employeeId) {
      employees = new ArrayList<Employee>(employeeId);
   }
   public void addEmployee(Employee employee) {
      employees.add(employee);
   }
   public void removeEmployee(Employee employee) {
      employees.remove(employee);
   }
   public int employeesListSize() {
      return employees.size();
   }
   @Override
   public Iterator<Employee> iterator() {
      return employees.iterator();
   }

}
 
public class EmployeeArrayListTester {
   public static void main(String[] args) {
      Employee emp1 = new Employee("John", "Smith", 21);
      Employee emp2 = new Employee("George","Smith", 41);
      EmployeeArrayList empList = new EmployeeArrayList();
      empList.addEmployee(emp1);
      empList.addEmployee(emp2);
      for (Employee emp : empList) {
         System.out.println(emp);
      }
   }
}

The code above when executed will output as:

EmployeeArrayList Test Output

First Name: John Last Name: Smith EmployeeId: 21
First Name: George Last Name: Smith EmployeeId: 41

3. Download the Source Code

This was an example of the Iterable Java Interface – java.lang.Iterable .

Download
You can download the full source code of this example here: Iterable Java Example – java.lang.Iterable Interface

Last updated on May 18th, 2020

Prasad Saya

Prasad Saya is a software engineer with over ten years’ experience in application development, maintenance, testing and consulting on various platforms. He is a certified Java and Java EE developer. At present his interest is in developing Java applications. He also has experience working with databases and ERP applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shrey Sharma
Shrey Sharma
5 years ago

I had a Question…Even though we imported ‘java.util.iterator’ we didnt import ‘java.lang.iterable’ right, but still we were able to implement interface “Iterable”…does that supposedly mean that…
Interfaces :
Iterable and Iterator import each other in there library source code. Please explain since i saw java api regarding these, it shows that Iterable and Iterator interface dont implement each still the Iterable interface has a function ‘iterator()’…how?

B S
B S
5 years ago
Reply to  Shrey Sharma

all classes/interfaces in java.lang Pacakge are automatically available in java

Back to top button