Category Archives: Core Java

Learn TreeMap in Java with Easy Programming Example

In this chapter you will learn:

  1. What is TreeMap class in Java?
  2. TreeMap Programming Example
  3. Constructors and Methods of TreeMap class in Java

What is TreeMap class in Java?

TreeMap class in Java uses Tree based Map to store elements. A Tree based map provides faster searching and retrieval of data and sorting is based on natural order of keys(More often it is an ascending order). A TreeMap is not implicitly Synchronized, it means multiple thread can access TreeMap but only one Thread have right to modify treemap. However, you can explicitly sync treemap class in java. More about TreeMap class in Java is listed below:

  1. A TreeMap class stores values based on Key.
  2. It contains only unique elements.
  3. It doesn’t accept null key however it can have multiple null values.
  4. It is almost same as HashMap but it maintains ascending order.

Constructors and Methods

Constructors of Java TreeMap class

Constructor Description
TreeMap() It is used to construct an empty tree map that will be sorted using the natural order of its key
TreeMap(Comparator comp) It is used to construct an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a tree map with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap sm) It is used to initialize a tree map with the entries from the SortedMap sm, which will be sorted in the same order as sm.
Methods Description
boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key.
boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value.
Object firstKey() It is used to return the first (lowest) key currently in this sorted map.
Object get(Object key) It is used to return the value to which this map maps the specified key.
Object lastKey() It is used to return the last (highest) key currently in this sorted map.
Object remove(Object key) It is used to remove the mapping for this key from this TreeMap if present.
void putAll(Map map) It is used to copy all of the mappings from the specified map to this map.
Set entrySet() It is used to return a set view of the mappings contained in this map.
int size() It is used to return the number of key-value mappings in this map.
Collection values() It is used to return a collection view of the values contained in this map.

Programming Example

import java.util.*;

public class TreeMap_Example
{
    public static void main(String[] args)
    {
        TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
        tm.put(1,"Jack");
        tm.put(3,"Clark");
        tm.put(2,"Steven");        
        tm.put(4,"Sarah");
        //Direct Printing
        System.out.println(tm);
        //Iteration Method 1
        PrintMethod1(tm);
        //Iteration Method 2
        PrintMethod2(tm);

        System.out.println("Item Removed : "+tm.remove(2));
        System.out.println("First Key of this list is : "+tm.firstKey());
        System.out.println("Last Key of this list is : "+tm.lastKey());
        System.out.println("Value of Key 3 is : "+tm.get(3));
    }
    //Iteration Method 1
    public static void PrintMethod1(TreeMap<Integer,String> tm)
    {
        Set set=tm.entrySet();
        Iterator itr=set.iterator();
        while(itr.hasNext())
        {
            Map.Entry me=(Map.Entry)itr.next();
            System.out.println("Key is : "+me.getKey()+" and Value is : "+me.getValue());
        }
    }
    //Iteration Method 2
    public static void PrintMethod2(TreeMap<Integer,String> tm)
    {
        for(Map.Entry m:tm.entrySet())
        {
            System.out.println("Key : "+m.getKey() + " | Value = "+m.getValue());
        }
    }
}

Output

{1=Jack, 2=Steven, 3=Clark, 4=Sarah}
Key is : 1 and Value is : Jack
Key is : 2 and Value is : Steven
Key is : 3 and Value is : Clark
Key is : 4 and Value is : Sarah
Key : 1 | Value = Jack
Key : 2 | Value = Steven
Key : 3 | Value = Clark
Key : 4 | Value = Sarah
Item Removed : Steven
First Key of this list is : 1
Last Key of this list is : 4
Value of Key 3 is : Clark
_

Summary

In this chapter you learned TreeMap class in Java with complete and easy programming example. My aim is to teach you Java with the help of easy programming not the help of bulky theory. Once you will be familiar with collection objects you will start exploring collection more deeply than tutorial.


LinkedHashMap Tutorial Java – Complete Programming Example

In this chapter you will learn:

  • What is LinkedHashMap in Java?
  • How to iterate through LinkedHashMap?
  • Programming Example
  • What is LinkedHashMap class in Java?

    LinkedHashMap is a combination of HashTable and Linked List and it stores items based on Key/Value pair. LinkedHashMap doesn’t allow inserting duplicate element. Point about LinkedHashMap are listed below:

    1. It contains values based on key.
    2. It contains only unique elements.
    3. It maintains insertion order as the keys were inserted.
    4. It is same as HashMap instead maintains insertion order.
    5. It maintains Doubly Linked List running through of all its objects.

    How to Initialize LinkedHashMap?

    LinkedHashMap<Key,Value> map = new LinkedHashMap<Key,Value>();

    Methods and Properties

    Constructor Description
    LinkedHashMap() It is used to construct a default LinkedHashMap.
    LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the given capacity.
    LinkedHashMap(int capacity, float fillRatio) It is used to initialize both the capacity and the fillRatio.
    LinkedHashMap(Map m) It is used to initialize the LinkedHashMap with the elements from the given Map class m.

    Methods

    Methods Description
    Object get(Object key) It is used to return the value to which this map maps the specified key.
    void clear() It is used to remove all mappings from this map.
    boolean containsKey(Object key) It is used to return true if this map maps one or more keys to the specified value.

    Programming Example

    import java.util.*;
    
    public class LinkedHashMap_Exmpl
    {
        public static void main(String[] args)
        {
            LinkedHashMap<Integer,String> Lmap=new LinkedHashMap<Integer,String>();
            Lmap.put(22,"Jack");
            Lmap.put(23,"Steven");
            Lmap.put(26,"Clark");
            Lmap.put(18, "Mathew");
            System.out.println("First Methods Iteration");
            PrintMethod1(Lmap);
            System.out.println("Second Methods Iteration");
            PrintMethod2(Lmap);
            System.out.println("Direct Printing");
            System.out.println(Lmap);
    
            //Remove an element
            System.out.println("Item removed : "+Lmap.remove(26));
            //New Item added
            System.out.println("Item Added : "+Lmap.put(19,"Sarah"));
            System.out.println(Lmap);
        }
        //Iterate Through LinkedHashMap Method 1
        public static void PrintMethod1(LinkedHashMap<Integer,String> lm)
        {
            Set set=lm.entrySet();
            Iterator itr=set.iterator();
            while(itr.hasNext())
            {
                Map.Entry me=(Map.Entry)itr.next();
                System.out.println("Key is : "+me.getKey()+" and Value is : "+me.getValue());
            }
        }
    
        //Iterate Through LinkedHashMap Method 1
        public static void PrintMethod2(LinkedHashMap<Integer,String> lm)
        {
            for(Map.Entry m:lm.entrySet())
            {
                System.out.println("Key : "+m.getKey() + " | Value = "+m.getValue());
            }
        }
    }

    Output

    First Methods Printing
    Key is : 22 and Value is : Jack
    Key is : 23 and Value is : Steven
    Key is : 26 and Value is : Clark
    Key is : 18 and Value is : Mathew
    Second Methods Printing
    Key : 22 | Value = Jack
    Key : 23 | Value = Steven
    Key : 26 | Value = Clark
    Key : 18 | Value = Mathew
    Direct Printing
    {22=Jack, 23=Steven, 26=Clark, 18=Mathew}
    Item removed : Clark
    Item Added : null
    {22=Jack, 23=Steven, 18=Mathew, 19=Sarah}
    _

    Summary

    In this chapter I’ve tried to explain LinkedHashMap with complete programming example in java. Almost the programming of all the collections classes are same and there is not too much differences. Once, you learn to write collection programming It gets very easy to learn rest of the collection objects. In the next chapter you will learn TreeMap class in Java.


    HashMap Tutorial Java – Complete Programming Example


    In this chapter you will learn

  • HashMap Tutorial Java
  • HashMap Programming Example
  • Constructores, Methdods and Properties of HashMap
  • What is HashMap Class in Java?

    HashMap is the same as HashTable class and only difference is it allows inserting null values and it is unsynchronized. HashMap doesn’t maintain insertion order and the elements can be stored at any places and iteration result might be different than the insertion order. It is also based on Map Interface and inherits all the functionality of Map Interface. More about HashMap class in java are listed below in the list.

    1. It contains value based on Key.
    2. It allows inserting null values and null keys.
    3. There may be only one null key in the list but can have multiple null values.
    4. It doesn’t maintain insertion order.
    5. It uses HashTable to implement the Map Interface.

    Constructors and Methods

    Constructor Description
    HashMap() It is used to construct a default HashMap.
    HashMap(Map m) It is used to initializes the hash map by using the elements of the given Map object m.
    HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
    HashMap(int capacity, float fillRatio) It is used to initialize both the capacity and fill ratio of the hash map by using its arguments

    Methods

    Methods Description
    void clear() It is used to remove all of the mappings from this map.
    boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key.
    boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value.
    boolean isEmpty() It is used to return true if this map contains no key-value mappings.
    Object clone() It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
    Set entrySet() It is used to return a collection view of the mappings contained in this map.
    Set keySet() It is used to return a set view of the keys contained in this map.
    Object put(Object key, Object value) It is used to associate the specified value with the specified key in this map.
    int size() It is used to return the number of key-value mappings in this map.
    Collection values() It is used to return a collection view of the values contained in this map.

    Programming Example

    import java.util.*;
    
    public class HashMap_Example
    {
        public static void main(String[] args)
        {
            HashMap<Integer,String> Hm=new HashMap<Integer,String>();
            Hm.put(1,"Steven");
            Hm.put(null,null);
            Hm.put(6,"Clark");
            Hm.put(3,"Jack");  
            //Direct Printing      
            System.out.println(Hm);
            //Method 1
            PrintMethod1(Hm);
            //Method 2
            PrintMethod2(Hm);
    
            //Remove an item()
            System.out.println("Item Removed : "+Hm.remove(1));
        }
        //Iteration Method 1
        public static void PrintMethod1(HashMap<Integer,String> hm)
        {
            Set set=hm.entrySet();
            Iterator itr=set.iterator();
            while(itr.hasNext())
            {
                Map.Entry me=(Map.Entry)itr.next();
                System.out.println("Key is : "+me.getKey()+" and Value is : "+me.getValue());
            }
        }
        //Iteration Method 2
        public static void PrintMethod2(HashMap<Integer,String> hm)
        {
            for(Map.Entry m:hm.entrySet())
            {
                System.out.println("Key : "+m.getKey() + " | Value = "+m.getValue());
            }
        }
    
    }

    Output

    {null=null, 1=Steven, 3=Jack, 6=Clark}
    Key is : null and Value is : null
    Key is : 1 and Value is : Steven
    Key is : 3 and Value is : Jack
    Key is : 6 and Value is : Clark
    Key : null | Value = null
    Key : 1 | Value = Steven
    Key : 3 | Value = Jack
    Key : 6 | Value = Clark
    Item Removed : Steven
    _

    Summary

    The HashMap class is another implementaion of Map Interface that uses HashTable. In this chapter you learn all about HashMap class in Java with complete programming example. In the next chapter you will learn LinkedHashMap class in Java.


    Java HashTable with Complete Programming Example

    In this chapter you will learn

    1. What is HashTable in Java?
    2. How to implement HashTable?
    3. HashTable programming example in java.

    What is HashTable?

    Java HashTable class stores item in key/value pair. All the items stored in hashtable is unique and it doesn’t allow null value. It inherits dictionary class and implement the map interface.

    To use HashTable in Java you need to add java.util library.

    Programming Example

    import java.security.Key;
    import java.util.*;
    class hashtable_example
    {
    public static void main(String[] args)
    {
        Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
        //Adding Items  
        System.out.println("Addint Items");  
        hm.put(1, "Steven");
        hm.put(2, "Clark");
        hm.put(3, "Jack");    
        System.out.println(hm);
        
        //Remove Item
        System.out.println("Removing Item");
        hm.remove(1);
        System.out.println(hm);
        
        //Find an Item
        System.out.println("Finding an Item");
        if(hm.get(2)=="Clark")
        {
         System.out.println("Hi, This is Clark");
        }
        else
        {
            System.out.println("Sorry, this is wrong number");
        }
    
        //Replace an Item
        System.out.println("Replacing an Item");
        hm.replace(2, "Steven Clark");
        System.out.println(hm);
    
        //Traverse Hashtable
        System.out.println("Traversing Through HashTable");
        Set<Integer> keys=hm.keySet();
        for(int i: keys)
        {
            System.out.println("Value of " + i +" = " + hm.get(i));
        }
    }
    }

    Output

    D:\JavaProgram>javac hashtable_example.java
    D:\JavaProgram>java hashtable_example
    Addint Items
    {3=Jack, 2=Clark, 1=Steven}
    Removing Item
    {3=Jack, 2=Clark}
    Finding an Item
    Hi, This is Clark
    Replacing an Item
    {3=Jack, 2=Steven Clark}
    Traversing Through HashTable
    Value of 3 = Jack
    Value of 2 = Steven Clark

    Summary

    In this tutorial you learned how to use HashTable in java programming. In the next chapter you will learn LinkedHashMap in Java.


    Learn Map Interface in Java with Programming Example

    map-interface
    In this chapter you will learn

    • What is Map Interface in Java?
    • Programming Example

    What is Map Interface in Java?

    Map Interface provides way to store value mapped by unique key. Later this key is used for retrieving data from collection. A map cannot contain duplicate value and each key map at most one value.

    Programming Example

    import java.util.*;
    class Map_Interface
    {
      public static void main(String[] args)
      {
        Map<String,String> mp=new HashMap<String,String>();
        mp.put("Java" , "1");
        mp.put("C#" , "2");
        mp.put("SQL" , "3");
        System.out.println(mp);
      }
    }
    

    Explanation

    In this programming Example we created a HashMap object and declare it with string type. We added values along with key pair in HashMap object and printed the table.

    Summary

    In this chapter you learned Map Interface in Java. In the next chapter you will learn about HashTable class in Java.


    Sorted Set in Java with Programming Example

    Sorted Set Java
    In this chapter you will learn
    What is Sorted Set in Java?
    Programming Example

    What is Sorted Set in Java?

    SortedSet is a set which stores its element in ascending order or sorted according to the elements natural ordering or according to comparator provided at set creation time. The traverse iterator traverse ascending order and several additional operations are provided to take advantage to the ordering.

    All elements must go through the comparable interface before inserting into sorted set and e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw the ClassCastException.

    Programming Example

    import java.util.*;
    
    class Sorted_Set
    {
      public static void main(String[] args)
      {
        SortedSet<String> s=new TreeSet<String>();
        s.add("Java");
        s.add("VB.Net");
        s.add("SQL");
        
        Iterator it=s.iterator();
        while(it.hasNext())
        {
          System.out.println(it.next());
        }
      }
    }
    

    Output

    Java
    SQL
    VB.Net
    _

    Summary

    In this chapter you learned how to use Sorted Set in java programming. As you can see that we have inserted elements in different order in TreeSet but when traverse using iterator and print result, it displayed result in ascending order. In the next chapter you will learn about Map Interface in Java.


    Learn TreeSet Class in Java with Programming Example

    treesetIn this chapter you will learn:

    1. What is TreeSet class in Java?
    2. Declaration and Methods of TreeSet Class
    3. Programming Example
    What is TreeSet class in Java?

    TreeSet provides an implementation of Set Interface based on TreeMap. The elements are ordered using their natural ordering depending on types of constructors. The TreeSet class is not synchronized it means you need to implement external synchronization when one thread changes TreeSet.

    Constructors

    Constructors Descriptions
    TreeSet() Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
    TreeSet(Collection<? extends E> c) Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
    TreeSet(Comparator<? super E> comparator) Constructs a new, empty tree set, sorted according to the specified comparator.
    TreeSet(SortedSet<E> s) Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

    Methods

    Methods Description
    boolean add(E e) Adds the specified element to this set if it is not already present.
    boolean addAll(Collection<? extends E> c) Adds all of the elements in the specified collection to this set.
    E ceiling(E e) Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
    void clear() Removes all of the elements from this set.
    Object clone() Returns a shallow copy of this TreeSet instance.
    Comparator<? super E> comparator() Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
    boolean contains(Object o) Returns true if this set contains the specified element.
    Iterator<E> descendingIterator() Returns an iterator over the elements in this set in descending order.
    NavigableSet<E> descendingSet() Returns a reverse order view of the elements contained in this set.
    E first() Returns the first (lowest) element currently in this set.
    E floor(E e) Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
    SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are strictly less than toElement.
    NavigableSet<E> headSet
    (E toElement, boolean inclusive)
    Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
    E higher(E e) Returns the least element in this set strictly greater than the given element, or null if there is no such element.
    boolean isEmpty() Returns true if this set contains no elements.
    Iterator<E> iterator() Returns an iterator over the elements in this set in ascending order.
    E last() Returns the last (highest) element currently in this set.
    E lower(E e) Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
    E pollFirst() Retrieves and removes the first (lowest) element, or returns null if this set is empty.
    E pollLast() Retrieves and removes the last (highest) element, or returns null if this set is empty.
    boolean remove(Object o) Removes the specified element from this set if it is present.
    int size() Returns the number of elements in this set (its cardinality).
    NavigableSet<E> subSet
    (E fromElement, boolean fromInclusive,
    E toElement, boolean toInclusive)
    Returns a view of the portion of this set whose elements range from fromElement to toElement.
    SortedSet<E> subSet
    (E fromElement, E toElement)
    Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
    SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
    NavigableSet<E> tailSet
    (E fromElement, boolean inclusive)
    Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.

    Methods Inherited From Class

    Class Methods
    java.util.AbstractSet equals(), hashCode(), removeAll()
    java.util.AbstractCollection containsAll(), retainAll(), toArray(), toArray(), toString()
    java.lang.Object finalize(), getClass(), notify(), notifyAll(), wait(), wait(), wait()
    java.util.Set containsAll(), equals(), hashCode(), removeAll(), retainAll(), toArray(), toArray()

    Declaration:

    LinkedHashSet hs=new LinkedHashSet();

    Programming Example

    import java.util.*;
    class TreeSet_Example
    {
      public static void main(String[] args)
      {
        //Declaration
        TreeSet ts=new TreeSet();
        
        //Adding Item into TreeSet
        ts.add("C#");
        ts.add("Java");
        ts.add("PHP");
        ts.add("SQL");
        ts.add("HTML");
        ts.add("CSS");
        
        //Printing TreeSet
        Iterator itr=ts.iterator();
        while(itr.hasNext())
        {
         System.out.print(itr.next() + " "); 
        }
        
        //Removing Item
        System.out.println("\nItem Removed : " + ts.remove("SQL"));
        
        //Printing
        System.out.println(ts);
      }
    }
    

    Output

    D:\JavaProgram>javac TreeSet_Example.java
    D:\JavaProgram>java TreeSet_ExampleC# CSS HTML Java PHP SQL
    Item Removed : true
    [C#, CSS, HTML, Java, PHP]
    _

    Summary

    In this chapter you learned about TreeSet class in Java with programming example. In the next chapter you will learn about SortedSet in Java.


    Learn LinkedHashSet Class in Java with Programming Example

    linkedhashsetIn this chapter you will learn:

    1. What is LinkedHashSet Class in Java
    2. Declaration and Methods of LinkedHashSet Class
    3. Programming Example
     What is LinkedHashSet Class in Java?

    LinkedHashSet is an implementation of HashSet in a linked list with predictable iteration order. It is different from HashSet as it maintains doubly linked list through its all entries. Linked list maintain the insertion order so the items are stored in Linked Hash Table as the order they inserted. It inherits all the methods of set operation and allow null element entry.

    Constructors

    Constructors Descriptions
    LinkedHashSet() Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
    LinkedHashSet(Collection<?
    extends E> c)
    Constructs a new linked hash set with the same elements as the specified collection.
    LinkedHashSet(int initialCapacity) Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
    LinkedHashSet(int initialCapacity,
    float loadFactor)
    Constructs a new, empty linked hash set with the specified initial capacity and load factor.

    Methods Inherited From Class

    Class Methods
    java.util.HashSet add(), clear(), clone(), contains(), isEmpty(), iterator(), remove(), size()
    java.util.AbstractSet equals(), hashCode(), removeAll()
    java.util.AbstractCollection addAll(), containsAll(), retainAll(), toArray(), toArray(), toString()
    java.lang.Object finalize(), getClass(), notify(), notifyAll(), wait(), wait(), wait()
    java.util.Set add(), addAll(), clear(), contains(), containsAll(), equals(), hashCode(), isEmpty(), iterator(), remove(), removeAll(), retainAll(), size(), toArray(), toArray()

    Declaration:

    LinkedHashSet hs=new LinkedHashSet();

    Programming Example

    import java.util.*;
    class LinkedHashSet_Example
    {
      public static void main(String[] args)
      {
        //Declaring LinkedHashSet
        LinkedHashSet hs=new LinkedHashSet();
        
        //Adding Item
        hs.add("C#");
        hs.add("Java");
        hs.add("SQL");
        hs.add("PHP");
        hs.add("HTML");
        
        //Printing LinkedHashSet
        Iterator itr=hs.iterator();
        while(itr.hasNext())
        {
          System.out.print(itr.next() + " ");
        }
        
        //Removing an Item
        System.out.println("\nItem Removed : "+ hs.remove("SQL"));
        
        //Printing 
        System.out.println(hs);
      }
    }
    
    
    

    Output

    D:\JavaProgram>javac LinkedHashSet_Example.java
    D:\JavaProgram>java LinkedHashSet_ExampleC# Java SQL PHP HTML
    Item Removed : true
    [C#, Java, PHP, HTML]
    _

    Summary

    In this chapter you learned LinkedHashSet class in java with programming example. In the next chapter you will learn TreeSet Class in Java.


    Learn HashSet Class in Java with Programming Example

    hashsetIn this chapter you will learn:

    1. What is HashSet Class in Java?
    2. Declaration and Methods of HashSet Class
    3. Programming Example
    What is HashSet class in Java?

    The HashSet Class implements the Set interface and stored items into a hash table. Iteration order might be different from insertion order. That means it takes no guarantee of element’s order as they inserted or no guarantee of same order result in each iteration. Some Fact about HashSet Class:

    1. It stores data in a Hash Table.
    2. Orders of elements are not guaranteed and you may get different order result in each iteration.
    3. It allows null elements.
    4. HashSet is not synchronized so if multiple threads are accessing this and one thread makes changes then you must synchronize HashSet Externally.

    Constructors

    Constructors Descriptions
    HashSet() Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
    HashSet(Collection<? extends E> c) Constructs a new set containing the elements in the specified collection.
    HashSet(int initialCapacity) Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
    HashSet(int initialCapacity, float loadFactor) Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

    Methods

    Methods Descriptions
    boolean add(E e) Adds the specified element to this set if it is not already present.
    void clear() Removes all of the elements from this set.
    Object clone() Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
    boolean contains(Object o) Returns true if this set contains the specified element.
    boolean isEmpty() Returns true if this set contains no elements.
    Iterator<E> iterator() Returns an iterator over the elements in this set.
    boolean remove(Object o) Removes the specified element from this set if it is present.
    int size() Returns the number of elements in this set (its cardinality).

     

    Methods Inherited From Class

    Class Methods
    java.util.AbstractSet equals(), hashCode(), removeAll()
    java.util.AbstractCollection addAll(), containsAll(), retainAll(), toArray(), toArray(), toString()
    java.lang.Object finalize(), getClass(), notify(), notifyAll(), wait(), wait(), wait()
    java.util.Set addAll(), containsAll(), equals(), hashCode(), removeAll(), retainAll(), toArray(), toArray()

    Declaration:

    HashSet h=new HashSet();
    

    Programming Example

    import java.util.*;
    class HashSet_Example
    {
      public static void main(String[] args)
      {
        HashSet; h=new HashSet();
        
        //Adding items in Hash Table
        h.add("PHP");
        h.add("Java");
        h.add("HTML");
        h.add("SQL");
        h.add("C#");
        
        //printing HashTable
        Iterator itr=h.iterator();
        while(itr.hasNext())
        {
          System.out.print(itr.next() + " ");
        }
       
        //Removing item from HashSet    
        System.out.println("\nItem Removed : "+h.remove("Java"));
        
        //Printing HashTable
        System.out.println(h);
      }
    }
    
    

    Output

    D:\JavaProgram>javac HashSet_Example.java
    D:\JavaProgram>java HashSet_ExampleSQL C# PHP HTML Java
    Item Removed : true
    [SQL, C#, PHP, HTML]
    _

    Summary

    In this chapter you have learned HashSet Class in Java with complete programming example. In the next chapter you will learn about LinkedHashSet Class.


    Learn Set Interface in Java with Programming Example

    set interface javaIn this chapter you will learn:

    What is Set Interface in Java?
    Set Interface Classes
    Programming Example

    What is Set Interface in Java?

    A Set is a collection which doesn’t allow adding duplicate entry in the list. It models the mathematical set abstraction. It contains methods only inherited from collection and adds restriction that duplicate elements are prohibited. Two set interfaces are equal if there elements are same.

    Types of Set

    There are three general purpose set implements in java that is listed below:

    1. HashSet It stores elements in hash table but orders of stored elements are not guaranteed.
    2. TreeSet It stores elements in red-black tree and orders of stored elements are based on their values. It is quite slower than HashSet.
    3. LinkedHashSet It stores elements in hash table with linked list and orders of stored elements are same as they inserted.

    Methods

    Methods Descriptions
    boolean add(E e) Adds the specified element to this set if it is not already present (optional operation).
    boolean addAll(Collection<? extends E> c) Adds all of the elements in the specified collection to this set if they’re not already present (optional operation).
    void clear() Removes all of the elements from this set (optional operation).
    boolean contains(Object o) Returns true if this set contains the specified element.
    boolean containsAll(Collection<?> c) Returns true if this set contains all of the elements of the specified collection.
    boolean equals(Object o) Compares the specified object with this set for equality.
    int hashCode() Returns the hash code value for this set.
    boolean isEmpty() Returns true if this set contains no elements.
    Iterator<E> iterator() Returns an iterator over the elements in this set.
    boolean remove(Object o) Removes the specified element from this set if it is present (optional operation).
    boolean removeAll(Collection<?> c) Removes from this set all of its elements that are contained in the specified collection (optional operation).
    boolean retainAll(Collection<?> c) Retains only the elements in this set that are contained in the specified collection (optional operation).
    int size() Returns the number of elements in this set (its cardinality).
    Object[] toArray() Returns an array containing all of the elements in this set.
    T[] toArray(T[] a) Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

    Declaration:

    Set s=new HashSet();
    

    Programming Example

    import java.util.*;
    class Set_Example
    {
      public static void main(String[] args)
      {
        Set s=new HashSet();
        s.add("PHP");
        s.add("Java");
        s.add("SQL");
        s.add("HTML");
        //Printing Hashset
        System.out.println(s);
        
        //Sorting Set in alphabetic order
        TreeSet st=new TreeSet(s);
        System.out.println(st);
        
        //Printing First Element
        System.out.println("First Element : " + st.first());
        
        //Printing Last Element
        System.out.println("Last Element : " + st.last());
        
      }    
    }
    
    

    Output

    D:\JavaProgram>javac Set_Example.java
    D:\JavaProgram>java Set_Example[SQL, PHP, HTML, Java]
    [HTML, Java, PHP, SQL]
    First Element : HTML
    Last Element : SQL
    _

    Summary

    In this chapter you saw quick review of Set Interface in java. In the next chapter you will learn HashSet Class in Java.