Implementing Iterable interface in Java to enable for-each loop based iterationPosted by Infocampus HR on January 4th, 2018 Iterable<T> and the for-each loop Typical for-each construct usage
Where list is an instance of java.util.List<MyClass>. Most of the important in-built collection types now support iteration using the enhanced for-each loop. This is by virtue of their implementing the interface Iterable<T>. In fact, any class which implements Iterable<T>, can be used in a for-each loop to iterate over the objects of type T which it holds or encapsulates. Extending this logic to the small code snippet we saw above – MyCollection which implements Iterable<MyClass>, can be used in a for-each loop to iterate through MyClass objects stored in it. Having understood the relationship between implementing Iterable interface and use of the implementing class in for-each loop, let us now understand how to go about implementing Iterable. How to implement Iterable<T> interface
So, if you have an API/Class containing a collection of String type of elements, and you want clients of this API to be able to access theString objects using a for-each loop, then your three steps of implementing Iterable<String> would go like this –
Simple, right! There is a small piece of logic missing though!!How do you get hold of an Iterator<String> instance pointing to your stored collection? The general practice in this case is to return the in-built Iterator instance of the collection class you use to store the iterable objects in your API. So, if you use a List<String> to store the String objects to be iterated, then you return Iterator<String> returned by List.iterator() method as the output of overridden Iterable.iterator() method. Let us see a Java code example to see how Iterable<T> implementation can be done. Java code example showing Iterable<T> implementation We will make Department class implement the Iterable<Employee> interface. Doing so would would allow us to iterate through employees of a department using the for-each loop just by getting hold of a Department instance. Let us see the code in action now, which will be followed by detailed explanation of the code. Java code example showing Iterable implementation
OUTPUT of the above code Tom Jones Harry Jones Ethan Hardy Nancy Smith Deborah Spright Explanation of the code
Summary Like it? Share it!More by this author |