Sunday, December 4, 2011

Java Set, SortedSet, HashSet, TreeSet, NavigableSet, LinkedHashSet Collections Implementation Example

The Set interface extends the Collection interface and, by definition, forbids duplicates within the collection. All the original methods are present and no new methods are introduced. The concrete Set implementation classes rely on the equals() method of the object added to check for equality. HashSet, TreeSet Classes The Collections Framework provides two general-purpose implementations of the Set interface: HashSet and TreeSet. More often than not, you will use a HashSet for storing your duplicate-free collection. For efficiency, objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation in Object, when creating your own classes to add to a HashSet remember to override hashCode(). The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. In order to work property, elements added to a TreeSet must be sortable. The Collections Framework adds support for Comparable elements and will be covered in detail later. For now, just assume a tree knows how to keep elements of the java.lang wrapper classes sorted. It is generally faster to add elements to a HashSet, then convert the collection to a TreeSet for sorted traversal. To optimize HashSet space usage, you can tune the initial capacity and load factor. The TreeSet has no tuning options, as the tree is always balanced, ensuring log(n) performance for insertions, deletions, and queries. Both HashSet and TreeSet implement the Cloneable interface. Implementation Demo Below

import java.util.SortedSet;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.LinkedHashSet;
import java.util.Collections;
import java.util.Set;
import java.util.NavigableSet;
import java.util.Iterator;
import java.util.Comparator;
import java.lang.Integer;

class Data {

 private String name;
 private String age;
 private String city; 

 Data( String n, String a, String c) {
  name = n;
  age = a;
  city = c;
 }

 public String toString() {
  return name + "\n" + age + "\n" + city;
 }

}          // Class Data Ends here


class SetDemo {
 public static void main(String args[] ) {

  // Using TreeSet create a new SortedSet
  SortedSet set1 = new TreeSet ();  // SortedSet is an interface and cannot be instantiated
  
  SetDemo ob = new SetDemo();

  set1.add(10);
  set1.add(90);     
  set1.add(50);
  set1.add(60);
  set1.add(20); 

  HashSet set2 =  new HashSet (set1);

  Iterator it = set2.iterator();
  while(it.hasNext() ) {
   System.out.println(it.next() );
  }
  System.out.println("Set Elements: " + set1);

  System.out.println("First Element in SortedSet: " + set1.first() );

  System.out.println("Last Element in SortedSet: " + set1.last() );

  System.out.println("Elements Less Than headSet(60) are =>  " + set1.headSet(60) );

  System.out.println("Elements between in subSet(10,60)=>  " + set1.subSet(10,60) );   // Start - (End-1)

  System.out.println("Elements between in Greater than or Equals to(50)=>  " + set1.tailSet(50) );  

  System.out.println("Set 2 Elements: " + set2);


  // HashSet Demo

  HashSet hset = new HashSet ();

  hset.add(new Data("Sundar", "25", "Chennai") );       // We can even add collection of Objects
  hset.add(new Data("Ashish", "24", "Lucknow") );       //in to any Collections and Manipulate
  hset.add(new Data("Abhinav", "22", "Delhi") );       //them

  Iterator ite = hset.iterator();
  System.out.println("Hash Set Data Items \n");
  while(ite.hasNext() ) {
   System.out.println(ite.next() );
  }

  // Display Using For-Each Statement

  System.out.println("Hash Set Data Items - Using for-each  \n");
  for(Data element : hset)
   System.out.println(element + "\n" );


  //NavigableSet Demo
  
  /* 
  
  NavigableSet interface is implemented by TreeSet() and concurrentSkipListSet() methods. Since later belongs to out of the scope    of collections framework, we are using the former one.
  
  NavigableSet nSet = new concurrentSkipListSet();
  
  */
  
  NavigableSet nSet = new TreeSet(set1);  // NavigableSet extends SortedSet ( TreeSet implements SortedSet) 
  
  NavigableSet rev1 = nSet.descendingSet();
  Iterator rev2  = nSet.descendingIterator();
  
  System.out.println("Navigable Set Data Items using desCendingIterator() \n");
  
  while(rev2.hasNext() ) {
   System.out.println(rev2.next() );
  }

  System.out.println("Navigable Set Data Items using desCendingSet() \n" + rev1);
  
  System.out.println("pollFirst:  \n" + nSet.pollFirst() );
 
  System.out.println("polllast :  \n" + nSet.pollLast() );

  System.out.println("Ceiling:  \n" + nSet.ceiling(50) );
  
  System.out.println("Floor:  \n" + nSet.floor(50) );

  System.out.println("Higher:  \n" + nSet.higher(50) );

  System.out.println("Lower:  \n" + nSet.lower(50) );
  
  System.out.println("Lower: using '40' \n" + nSet.lower(40) );
  
 }    // Main Ends Here

}      // Class Ends Here

No comments:

Post a Comment