Sunday 1 November 2015

How to fetch elements from HashSet



To fetch an elements of Hashset, you can call the iterator() method to get an Iterator:
    
   public Iterator iterator()  

Since the elements of hash set are unordered, the order of the elements returned has nothing to do with the order in which they were inserted or added. And as the capacity of the hash set changes, the elements may be reordered.

For example:-

 import java.util.Arrays;  
 import java.util.HashSet;  
 import java.util.Iterator;  
 import java.util.Set;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class HashSetIteration {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String str[] = { "a", "b", "c", "d", "e" };  
           Set<String> set = new HashSet<String>(Arrays.asList(str));  
           Iterator<String> itr = set.iterator();  
           while (itr.hasNext()) {  
                System.out.println(itr.next());  
           }  
      }  
 }  

 Output:  
 d  
 e  
 b  
 c  
 a  

Remember that order doesn’t matter as long as each element in the set is displayed.


Happy Reading .

No comments:

Post a Comment