Java Iterable: How to Iterate Elements

In Java, you can use the iterator() method of the Iterable interface to obtain an Iterator object, which can then be used to iterate through all elements. Below is an example code:

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("orange");

        Iterable<String> iterable = list;

        Iterator<String> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }
}

In the above example, we first created an ArrayList object and added some elements to it. Then we converted the ArrayList object into an object that implements the Iterable interface, and obtained an Iterator object through the iterator() method. Finally, we used a while loop and the Iterator object to iterate through all elements and output them.

bannerAds