Skip to main content

Set interface in java with example

Read this article to know what is Set interface and its implemented classes in java with examples programs.  Set interface  represents a group of elements arranged as like an array. Set interface will grown dynamically when the elements are stored into it. Set will not allow duplicate elements to store into it. Set interface implemented classes are,
  • HashSet<T>
  • TreeSet<T>
  • LinkedHashSet<T>
          <T> represents the generic type of the storing element in set.

Set interface methods:
  • boolean add(Object) : Ensures the Set holds the argument. The Object is added only if it isn't already in the Set. Returns false if the Object was not added to the Set.
  • void clear() : Removes all elements from the Set.
  • boolean contains(Object) : Returns true if the Set contains the argument.
  • boolean isEmpty() : Returns true if the Set contains no elements.
  • Iterator iterator() : Returns an Iterator object which can be used to traverse through the Set. (See last month's article for information on the Iterator interface.)
  • boolean remove(Object) : Removes the argument from the Set. Returns true if the argument was removed.
  • int size() : Returns the number of elements in the Set.
  • Object[] toArray() : Returns an Object array containing all the elements in the Set.
HashSet:   
HashSet represents a set of elements (Objects). It does not guarantee the order of elements. It does not allow duplicate elements to be stored.  We can create the HashSet class as
class HashSet<T>

Here, T represents the Generic type parameter. It represents which type of elements are being stored into the HashSet .
HashSet<String> hs = new HashSet<String>();

In the above line represents the HashSet<String> object creation and it store the String type of values into it.

The HashSet doesn't add any additional methods beyond those found in the Set interface. Any object place in HashSet must implement the hashCode() and equals() methods. The HashSet default capacity is 16 and the default load factor is 0.75 . Load factor determines the point where the capacity of the HashSet would be increased internally.

Ex: Here is the example program which will shows the use of HashSet and Iterator .
package com.javatbrains.collections;

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

public class HashSetUse {

     public static void main(String[] args) {
          // Create a HashSet to store Strings
          HashSet<String> hset = new HashSet<String>();

          // Store some String elements
          hset.add("India");
          hset.add("America");
          hset.add("Pakistan");
          hset.add("India");
          hset.add("America");

          // Add iterator to hset
          Iterator<String> it = hset.iterator();

          // Display element by element using Iterator
          System.out.println("Elements using iterator:");
          while (it.hasNext()) {
              String country = (String) it.next();
              System.out.println(country);
          }
     }

}
OutPut:
     Elements using iterator:
          America
          Pakistan
          India

Steps:
  • Create HashSet object by using new operator.
  • Add some String type elements into HashSet object.
  • Create and Iterator instance by using HashSet object.
  • Get each element one by one from iterator by processing through while loop.
As of I mentioned in the above, classes that are to be stored in HashSet must implement the hashCode() and equals() methods. Here is an example.
package com.javatbrains.collections;

public class Person {
     private String aadhar;
     private String name;

     public String getName() {
          return name;
     }

     public String getAadhar() {
          return aadhar;
     }

     public boolean equals(Object obj) {
          boolean retValue = false;
          if (obj instanceof Person) {
               Person e = (Person) obj;
              retValue = aadhar.equals(e.getAadhar());
          }
          return retValue;
     }

     public int hashCode() {
          return aadhar.hashCode();
     }
}

LinkedHashSet:
This is an subclass of HashSet class and does not contain any additional members on its own.
class LinkedHashSet<T>

          Here, <T> represents the generic type parameter. It represents the data type of elements being stored into the LinkedHashSet . LinkedHashSet Internally uses a linked list to store the elements.

TreeSet:
The TreeSet class guarantees that the Objects in the Set will be sorted in ascending order by either the Object's natural order or by the Comparator provided to the constructor of the TreeSet. Searching for an item in TreeSet will be slower than in a HashSet because the " Hashing algorithm" gives better performance than the compareTo() method which is used to locate items in a TreeSet.  TreeSet added several methods to the Set interface,
  • Object first(): Gets the first element from the sorted set.
  • Object last() : Gets the last element from the sorted set.
  • SortedSet headSet(Object toElement): Returns a view of the portion of this set whose elements are less than toElement.
  • SortedSet tailSet(Object fromElement): Returns a view of the portion of this set whose elements are greater than or equal to from Element.
  • SortedSet subSet(Object fromElement, Object toElement): Returns a view of the portion of this set whose starting element is greater than or equal to from Element and whose ending element is less than toElement.
Ex: Here is the example program to show use of TreeSet and Iterator.
package com.javatbrains.collections;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetUse {

     public static void main(String[] args) {
          TreeSet<String> tset = new TreeSet<String>();

          // Store some String elements
          tset.add("India");
          tset.add("America");
          tset.add("Pakistan");
          tset.add("India");
          tset.add("America");

          // Add iterator to tset
          Iterator<String> it = tset.iterator();

          // Display element by element using Iterator
          System.out.println("Elements using iterator:");
          while (it.hasNext()) {
              String country = (String) it.next();
              System.out.println(country);
          }
     }

}
OutPut:
     Elements using iterator:
          America
          India
          Pakistan
         
If you have observed the output of the previous classes,   HashSetUse class doesn't give any ordered output. But, TreeSetUse.java class gives you ascending order by default.

Sorting Collections:
We have two options to sort elements in TreeSet.
  • Comparable interface
  • Comparator class
If you want to use Comparable interface, objects of the class should be implements the Comparable interface in the TreeSet . Comparable interface has single method,
int compareTo(Object o)

The compareTo() method will return a negative number, zero, or positive number depending on whether the Object is less than, equal to, or greater than the Object argument.
package com.javatbrains.collections;

public class Person implements Comparable{
     private String aadhar;
    
     public String getAadhar() {
          return aadhar;
     }

     // The comparison can be done on any field we choose.
     // For this example we have decided to sort by empNum.
     public int compareTo(Object obj) {
          Person e  = (Person)obj;
          return aadhar.compareTo(e.getAadhar( ));
     }
}

The second option is provide a Comparator for the TreeSet to use. The advantage of the Comparator is that we can create multiple Comparator  that can be used to sort our TreeSet in multiple ways.
package com.javatbrains.collections;

import java.util.Comparator;

public class Person implements Comparable {
     private String aadhar;
     private String name;

     public String getName() {
          return name;
     }

     public String getAadhar() {
          return aadhar;
     }

     public static final Comparator AADHAR_ORDER = new Comparator() {
          public int compare(Object o1, Object o2) {
              Person p1 = (Person) o1;
              Person p2 = (Person) o2;
              return p1.getAadhar().compareTo(p2.getAadhar());
          }
     };
    
     public static final Comparator NAME_ORDER = new Comparator() {
          public int compare(Object o1, Object o2) {
              Person p1 = (Person) o1;
              Person p2 = (Person) o2;
              return p1.getName().compareTo(p2.getName());
          }
     };
}

As I have mentioned in the below, I will use the above Comparator NAME_ORDER in another class to keep Person names in an order.
TreeSet ts = new TreeSet(Person.NAME_ORDER );

The same option used for TreeSet can use any of the collection. A collection can be sorted by using the static sort method of the Collections class.
Collections.sort(empArrayList);

            empArrayList – is an Arraylist object.

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...