Saturday, March 24, 2018

Some ways to iterate set

Below are some of the ways to iterate set in java. However still lot of other ways to do the same. But these are the basic you can use at any time easily.

Let see with an example.

1. Using Iterator
2. An  enhanced for loop
3. An enhanced for loop with java8

1. Using an Iterator


import java.util.HashSet;
import java.util.Iterator;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("One");
     hset.add("Two");
     hset.add("Three");
     hset.add("Four");
     hset.add("Five");
 
     Iterator<String> it = hset.iterator();
     while(it.hasNext()){
        System.out.println(it.next());
     }
  }
}

Output:
Five
One
Four
Two
Three

Note: No ordered here.- Check output carefully.

2. An enhanced for loop


import java.util.HashSet;
import java.util.Set;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("First");
     hset.add("Second");
     hset.add("Third");
     hset.add("Fourth");
     hset.add("Fifth");
 
     for (String temp : hset) {
        System.out.println(temp);
     }
  }
}

Output:

Second
Third
First
Fourth
Fifth



3. An enhanced for loop with java8


import java.util.HashSet;
import java.util.Set;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Test");
     hset.add("Second");
     hset.add("Third");
     hset.add("Fourth");
     hset.add("Fifth");
 
     hset.forEach(System.out::println);
  }
}

Output:

Second
Test
Third
Fourth
Fifth







No comments:

Post a Comment