Different ways to loop / Iterate HashSet Using java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn about how to iterate or loop Set collection object using different ways.

Loop Hashset using four different ways.

Using Iterator

Iterate Set collection using java.util.Iterator

Iterator iter = colors.iterator();

Using for each loop

It is introduced in Java 5 to enhance the looping mechanism. It is mainly used to traverse array or collection elements. Due to its simple structure your looping code is more readable and clean.

for (String color: colors) {
    System.out.println(color);
}

Using Enumeration

It is similar to Iterator interface. Enumeration interface generates a series of elements and used to traverse collection elements.

for (Enumeration  color = Collections.enumeration(colors); color.hasMoreElements();) {
    System.out.println(color.nextElement());
}

Using Array Object

Returns an array containing all of the elements in this collection in proper sequence. Once you get the array object then loop it using for loop.

Object[] colorObj = colors.toArray();
for (int i = 0; i < colorObj.length; i++) {
    System.out.println(colorObj[i]);
}

Complete Hashset Looping Example

package com.technicalkeeda.app;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashsetIteratorExample {
    public static void main(String[] args) {
        Set  colors = new HashSet  ();

        colors.add("Red");
        colors.add("Blue");
        colors.add("Green");
        colors.add("Black");

        System.out.println("Using Iterator---");

        Iterator  iter = colors.iterator();
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }

        System.out.println("\nUsing Loop---");

        for (String color: colors) {
            System.out.println(color);
        }

        System.out.println("\nUsing Enumeration---");
        for (Enumeration  color = Collections.enumeration(colors); color.hasMoreElements();) {
            System.out.println(color.nextElement());
        }

        System.out.println("\nUsing Array---");
        Object[] colorObj = colors.toArray();

        for (int i = 0; i < colorObj.length; i++) {
            System.out.println(colorObj[i]);
        }

    }
}

Output

Using Iterator---
Red
Blue
Black
Green

Using Loop---
Red
Blue
Black
Green

Using Enumeration---
Red
Blue
Black
Green

Using Array---
Red
Blue
Black
Green


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0280 seconds.