Saturday, May 11, 2013

Linked HashSet Example

LinkedHashSet Example :

LinkedHashSet is the class which is available in java.util package.

The main advantage of LinkedHashSet is, it preserves the order of the elements. I mean while iterating the
LinkedHashSet  the elements are retrieve in the same order how we insert into it.

LinkedHashSet implements the Set interface, it allows the Null values and allows unique elements.

LinkedHashSet  has lot of methods which are very much useful.

LinkedHashSet which extends the java.util.HashSet Class and all the methods which are available in HashSet class are available in the LinkedHashSet class.



 import java.util.Iterator;  
 import java.util.LinkedHashSet;  
      //LinkeHashSetExample Example Java  
      public class LinkeHashSetExample {  
        public static void main(String[] args) {  
          //LinkeHashSetExample, it preserves order of the elements.  
             LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();  
             linkedHashSet.add("Item1");  
             linkedHashSet.add("Item2");  
             linkedHashSet.add("Item2");  
             linkedHashSet.add("Item4");  
             linkedHashSet.add("Item3");  
             linkedHashSet.add(null);  
             linkedHashSet.add(null);  
          Iterator<String> iterator = linkedHashSet.iterator();  
          while (iterator.hasNext()) {  
            System.out.println(iterator.next());  
          }  
          linkedHashSet.remove("Item2");  
          System.out.println("After removing Item2...");  
          // after removing jsp  
          iterator = linkedHashSet.iterator();  
          while (iterator.hasNext()) {  
            System.out.println(iterator.next());  
          }  
          if (linkedHashSet.contains("Item3")) {  
            System.out.println("Item3 available");  
          }  
        }  
      }  

Output : Item1
Item2
Item4
Item3
null
After removing Item2...
Item1
Item4
Item3
null
Item3 available

1 comment :

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.