Using iterator

To iterate through each element present within a list, we use the iterator method. We need to create another object for this Iterator class, along with the String argument type:

        Iterator<String> i=hs.iterator();

Imagine that we have a set of elements and they are in order starting from zero, one, two, and so on. iterator goes through each element starting from zero and prints the element present at each value. We have created an object for iterator and we print the values as follows:

        System.out.println(i.next());
System.out.println(i.next());

The first instance of i.next() will print the values present at the zero index and the next i.next() instance prints the value at index one. If we have a set where we have around 100 values, we will have to use the while loop:

        while(i.hasNext())
{
System.out.println(i.next());
}

Here, we have used the hasNext method, which checks the set for next values. If there are values present in the next index, it'll return true and if not, it returns false. In our case, it'll return true for 100 values and false after that, and exit the while loop.

This is how you can iterate through the objects present in the Set interface using iterator. If you are working on automation testing, such as Selenium, you'll be using this while loop frequently.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.8.34