Skip to main content

Java Collections

Collections in Java

The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
  1. Interfaces and classes.
  2. Algorithm.

Hierarchy of Collection Framework

The java.util package contains all the classes and interfaces for the Collection framework.
Hierarchy of Java Collection framework


Iterable Interface

The Iterable interface is the root interface for all the collection classes.
It contains only one abstract method. i.e.,
  1. Iterator<T> iterator()  
It returns the iterator over the elements of type T.

Collection Interface

The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have. 

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:
No.MethodDescription
1public boolean add(E e)It is used to insert an element in this collection.
2public boolean addAll(Collection<? extends E> c)It is used to insert the specified collection elements in the invoking collection.
3public boolean remove(Object element)It is used to delete an element from the collection.
4public boolean removeAll(Collection<?> c)It is used to delete all the elements of the specified collection from the invoking collection.
5default boolean removeIf(Predicate<? super E> filter)It is used to delete all the elements of the collection that satisfy the specified predicate.
6public boolean retainAll(Collection<?> c)It is used to delete all the elements of invoking collection except the specified collection.
7public int size()It returns the total number of elements in the collection.
8public void clear()It removes the total number of elements from the collection.
9public boolean contains(Object element)It is used to search an element.
10public boolean containsAll(Collection<?> c)It is used to search the specified collection in the collection.
11public Iterator iterator()It returns an iterator.
12public Object[] toArray()It converts collection into array.
13public <T> T[] toArray(T[] a)It converts collection into array. Here, the runtime type of the returned array is that of the specified array.
14public boolean isEmpty()It checks if collection is empty.
15default Stream<E> parallelStream()It returns a possibly parallel Stream with the collection as its source.
16default Stream<E> stream()It returns a sequential Stream with the collection as its source.
17default Spliterator<E> spliterator()It generates a Spliterator over the specified elements in the collection.
18public boolean equals(Object element)It matches two collections.
19public int hashCode()It returns the hash code number of the collection.




List Interface

List Interface is the subinterface of Collection. It contains index-based methods to insert and delete elements. 

List Interface declaration

  1. public interface List<E> extends Collection<E>  

Methods of Java List Interface

MethodDescription
void add(int index, E element)It is used to insert the specified element at the specified position in a list.

boolean addAll(int index, Collection<? extends E> c)It is used to append all the elements in the specified collection, starting at the specified position of the list.
E get(int index)It is used to fetch the element from the particular position of the list.

int lastIndexOf(Object o)It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
int indexOf(Object o)It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index)It is used to remove the element present at the specified position in the list.

E set(int index, E element)It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of specified comparator.
Listiterator  listIterator()It is used to create iterate the elements in a list.
List<E> subList(int fromIndex, int toIndex)It is used to fetch all the elements lies within the given range.

ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It implements List interface.
The important points about Java ArrayList class are:
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.

ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.
  1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

Constructors of Java ArrayList

ConstructorDescription
ArrayList()It is used to build an empty array list.
ArrayList(Collection<? extends E> c)It is used to build an array list that is initialized with the elements of the collection c.
ArrayList(int capacity)It is used to build an array list that has the specified initial capacity.

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.
Let's see the old non-generic example of creating java collection.
  1. ArrayList al=new ArrayList();//creating old non-generic arraylist  
Let's see the new generic example of creating java collection.
  1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist  
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of objects in it. If you try to add another type of object, it gives compile time error.
For more information on Java generics, click here Java Generics Tutorial.

Add elements in ArrayList Example

  1. import java.util.*;  
  2.  
  3. import java.util.*;  
  4.  class ArrayList7{  
  5.  public static void main(String args[]){  
  6.   ArrayList<String> al=new ArrayList<String>();  
  7.            System.out.println("Initial list of elements: "+al);  
  8.            //Adding elements to the end of the list  
  9.            al.add("Ravi");  
  10.            al.add("Vijay");  
  11.            al.add("Ajay");  
  12.            System.out.println("After invoking add(E e) method: "+al);  
  13.            //Adding an element at the specific position  
  14.            al.add(1"Gaurav");  
  15.            System.out.println("After invoking add(int index, E element) method: "+al);  
  16.            ArrayList<String> al2=new ArrayList<String>();  
  17.            al2.add("Sonoo");  
  18.            al2.add("Hanumat");  
  19.            //Adding second list elements to the first list  
  20.            al.addAll(al2);  
  21.            System.out.println("After invoking addAll(Collection<? extends E> c) method: "+al);  
  22.            ArrayList<String> al3=new ArrayList<String>();  
  23.            al3.add("John");  
  24.            al3.add("Rahul");  
  25.            //Adding second list elements to the first list at specific position  
  26.            al.addAll(1, al3);  
  27.            System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+al);  
  28.              
  29.  }  
  30. }  
  31.   
 Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method: 
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method: 
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

Java ArrayList example to remove elements

Here, we see different ways to remove an element.
  1. import java.util.*;  
  2.  class ArrayList8 {  
  3.   
  4.         public static void main(String [] args)  
  5.         {  
  6.           ArrayList<String> al=new ArrayList<String>();  
  7.           al.add("Ravi");    
  8.           al.add("Vijay");    
  9.           al.add("Ajay");   
  10.           al.add("Anuj");  
  11.           al.add("Gaurav");  
  12.           System.out.println("An initial list of elements: "+al);   
  13.           //Removing specific element from arraylist  
  14.           al.remove("Vijay");  
  15.           System.out.println("After invoking remove(object) method: "+al);   
  16.           //Removing element on the basis of specific position  
  17.           al.remove(0);  
  18.           System.out.println("After invoking remove(index) method: "+al);   
  19.             
  20.           //Creating another arraylist  
  21.           ArrayList<String> al2=new ArrayList<String>();    
  22.           al2.add("Ravi");    
  23.           al2.add("Hanumat");    
  24.           //Adding new elements to arraylist  
  25.           al.addAll(al2);  
  26.           System.out.println("Updated list : "+al);   
  27.           //Removing all the new elements from arraylist  
  28.           al.removeAll(al2);  
  29.           System.out.println("After invoking removeAll() method: "+al);   
  30.           //Removing elements on the basis of specified condition  
  31.           al.removeIf(str -> str.contains("Ajay"));   //Here, we are using Lambda expression   
  32.           System.out.println("After invoking removeIf() method: "+al);  
  33.           //Removing all the elements available in the list  
  34.           al.clear();  
  35.           System.out.println("After invoking clear() method: "+al);   
  36.        }  
  37.     }                   
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []


Java ArrayList example of retainAll() method

  1. import java.util.*;  
  2. class ArrayList9{  
  3.  public static void main(String args[]){  
  4.   ArrayList<String> al=new ArrayList<String>();  
  5.   al.add("Ravi");  
  6.   al.add("Vijay");  
  7.   al.add("Ajay");  
  8.   ArrayList<String> al2=new ArrayList<String>();  
  9.   al2.add("Ravi");  
  10.   al2.add("Hanumat");  
  11.   al.retainAll(al2);  
  12.   System.out.println("iterating the elements after retaining the elements of al2");  
  13.   Iterator itr=al.iterator();  
  14.   while(itr.hasNext()){  
  15.    System.out.println(itr.next());  
  16.   }  
  17.  }  
  18. }  
       iterating the elements after retaining the elements of al2
       Ravi

Java ArrayList example of isEmpty() method

  1. import java.util.*;  
  2.  class ArrayList10{  
  3.   
  4.         public static void main(String [] args)  
  5.         {  
  6.           ArrayList<String> al=new ArrayList<String>();  
  7.           System.out.println("Is ArrayList Empty: "+al.isEmpty());  
  8.           al.add("Ravi");    
  9.           al.add("Vijay");    
  10.           al.add("Ajay");    
  11.           System.out.println("After Insertion");  
  12.           System.out.println("Is ArrayList Empty: "+al.isEmpty());   
  13.        }  
  14.     }      
Is ArrayList Empty: true
After Insertion
Is ArrayList Empty: false

Java ArrayList example of set() and get() method

  1. import java.util.*;  
  2.  class ArrayList11 {  
  3.   
  4.         public static void main(String [] args)  
  5.         {  
  6.           ArrayList<String> al=new ArrayList<String>();  
  7.               al.add("Ravi");    
  8.               al.add("Vijay");    
  9.               al.add("Ajay");    
  10.               System.out.println("Before update: "+al.get(1));   
  11.               //Updating an element at specific position  
  12.               al.set(1,"Gaurav");  
  13.               System.out.println("After update: "+al.get(1));   
  14.        }  
  15.     }         
Before update: Vijay
After update: Gaurav

User-defined class objects in Java ArrayList

Let's see an example where we are storing Student class object in an array list.
  1. class Student{  
  2.   int rollno;  
  3.   String name;  
  4.   int age;  
  5.   Student(int rollno,String name,int age){  
  6.    this.rollno=rollno;  
  7.    this.name=name;  
  8.    this.age=age;  
  9.   }  
  10. }  
  1. import java.util.*;  
  2.  class ArrayList5{  
  3.  public static void main(String args[]){  
  4.   //Creating user-defined class objects  
  5.   Student s1=new Student(101,"Sonoo",23);  
  6.   Student s2=new Student(102,"Ravi",21);  
  7.   Student s2=new Student(103,"Hanumat",25);  
  8.   //creating arraylist  
  9.   ArrayList<Student> al=new ArrayList<Student>();  
  10.   al.add(s1);//adding Student class object  
  11.   al.add(s2);  
  12.   al.add(s3);  
  13.   //Getting Iterator  
  14.   Iterator itr=al.iterator();  
  15.   //traversing elements of ArrayList object  
  16.   while(itr.hasNext()){  
  17.     Student st=(Student)itr.next();  
  18.     System.out.println(st.rollno+" "+st.name+" "+st.age);  
  19.   }  
  20.  }  
  21. }  
       101 Sonoo 23
       102 Ravi 21
       103 Hanumat 25

Java LinkedList class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to occur.
  • Java LinkedList class can be used as a list, stack or queue.

Doubly Linked List

In the case of a doubly linked list, we can add or remove elements from both sides.
java LinkedList class using doubly linked list

LinkedList class declaration

Let's see the declaration for java.util.LinkedList class.
  1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable  

Constructors of Java LinkedList

ConstructorDescription
LinkedList()It is used to construct an empty list.
LinkedList(Collection<? extends E> c)It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection's iterator.

Java LinkedList example to add elements

Here, we see different ways to add elements.
  1. import java.util.*;  
  2. public class LinkedList2{  
  3.  public static void main(String args[]){  
  4.  LinkedList<String> ll=new LinkedList<String>();  
  5.            System.out.println("Initial list of elements: "+ll);  
  6.            ll.add("Ravi");  
  7.            ll.add("Vijay");  
  8.            ll.add("Ajay");  
  9.            System.out.println("After invoking add(E e) method: "+ll);  
  10.            //Adding an element at the specific position  
  11.            ll.add(1"Gaurav");  
  12.            System.out.println("After invoking add(int index, E element) method: "+ll);  
  13.            LinkedList<String> ll2=new LinkedList<String>();  
  14.            ll2.add("Sonoo");  
  15.            ll2.add("Hanumat");  
  16.            //Adding second list elements to the first list  
  17.            ll.addAll(ll2);  
  18.            System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll);  
  19.            LinkedList<String> ll3=new LinkedList<String>();  
  20.            ll3.add("John");  
  21.            ll3.add("Rahul");  
  22.            //Adding second list elements to the first list at specific position  
  23.            ll.addAll(1, ll3);  
  24.            System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);  
  25.            //Adding an element at the first position  
  26.            ll.addFirst("Lokesh");  
  27.            System.out.println("After invoking addFirst(E e) method: "+ll);  
  28.            //Adding an element at the last position  
  29.            ll.addLast("Harsh");  
  30.            System.out.println("After invoking addLast(E e) method: "+ll);  
  31.              
  32.  }  
  33. }  
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method: 
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method: 
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method: 
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method: 
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements

Here, we see different ways to remove an element.
  1. import java.util.*;  
  2. public class LinkedList3 {  
  3.   
  4.         public static void main(String [] args)  
  5.         {  
  6.            LinkedList<String> ll=new LinkedList<String>();  
  7.            ll.add("Ravi");  
  8.            ll.add("Vijay");  
  9.            ll.add("Ajay");  
  10.            ll.add("Anuj");  
  11.            ll.add("Gaurav");  
  12.            ll.add("Harsh");  
  13.            ll.add("Virat");  
  14.            ll.add("Gaurav");  
  15.            ll.add("Harsh");  
  16.            ll.add("Amit");  
  17.            System.out.println("Initial list of elements: "+ll);  
  18.          //Removing specific element from arraylist  
  19.               ll.remove("Vijay");  
  20.               System.out.println("After invoking remove(object) method: "+ll);   
  21.          //Removing element on the basis of specific position  
  22.               ll.remove(0);  
  23.               System.out.println("After invoking remove(index) method: "+ll);   
  24.               LinkedList<String> ll2=new LinkedList<String>();  
  25.               ll2.add("Ravi");  
  26.               ll2.add("Hanumat");  
  27.          // Adding new elements to arraylist  
  28.               ll.addAll(ll2);  
  29.               System.out.println("Updated list : "+ll);   
  30.          //Removing all the new elements from arraylist  
  31.               ll.removeAll(ll2);  
  32.               System.out.println("After invoking removeAll() method: "+ll);   
  33.          //Removing first element from the list  
  34.               ll.removeFirst();  
  35.               System.out.println("After invoking removeFirst() method: "+ll);  
  36.           //Removing first element from the list  
  37.               ll.removeLast();  
  38.               System.out.println("After invoking removeLast() method: "+ll);  
  39.           //Removing first occurrence of element from the list  
  40.               ll.removeFirstOccurrence("Gaurav");  
  41.               System.out.println("After invoking removeFirstOccurrence() method: "+ll);  
  42.           //Removing last occurrence of element from the list  
  43.               ll.removeLastOccurrence("Harsh");  
  44.               System.out.println("After invoking removeLastOccurrence() method: "+ll);  
  45.   
  46.               //Removing all the elements available in the list       
  47.               ll.clear();  
  48.               System.out.println("After invoking clear() method: "+ll);   
  49.        }  
  50.     }                   
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Java LinkedList Example to reverse a list of elements

  1. import java.util.*;  
  2. public class LinkedList4{  
  3.  public static void main(String args[]){  
  4.   
  5.   LinkedList<String> ll=new LinkedList<String>();  
  6.            ll.add("Ravi");  
  7.            ll.add("Vijay");  
  8.            ll.add("Ajay");  
  9.            //Traversing the list of elements in reverse order  
  10.            Iterator i=ll.descendingIterator();  
  11.            while(i.hasNext())  
  12.            {  
  13.                System.out.println(i.next());  
  14.            }  
  15.              
  16.  }  
  17. }  
Output: Ajay
Vijay
Ravi


Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
  1. import java.util.*;  
  2. public class TestJavaCollection3{  
  3. public static void main(String args[]){  
  4. Vector<String> v=new Vector<String>();  
  5. v.add("Ayush");  
  6. v.add("Amit");  
  7. v.add("Ashish");  
  8. v.add("Garima");  
  9. Iterator<String> itr=v.iterator();  
  10. while(itr.hasNext()){  
  11. System.out.println(itr.next());  
  12. }  
  13. }  
  14. }  
Output:
Ayush
Amit
Ashish
Garima

Stack

The stack is the subclass of Vector.
 It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.
  1. import java.util.*;  
  2. public class TestJavaCollection4{  
  3. public static void main(String args[]){  
  4. Stack<String> stack = new Stack<String>();  
  5. stack.push("Ayush");  
  6. stack.push("Garvit");  
  7. stack.push("Amit");  
  8. stack.push("Ashish");  
  9. stack.push("Garima");  
  10. stack.pop();  
  11. Iterator<String> itr=stack.iterator();  
  12. while(itr.hasNext()){  
  13. System.out.println(itr.next());  
  14. }  
  15. }  
  16. }  
Output:
Ayush
Garvit
Amit
Ashish

Ways to iterate the elements of the collection in java

There are various ways to traverse the collection elements:
  1. By Enumerator interface.
  2. By Iterator interface
  3. By for-each loop.
  4. By ListIterator interface.
  5. By for loop.
  6. By forEach() method.

Enumeration interface

The Enumeration interface defines the methods by which you can enumerate the elements in a collection of objects.
This is legacy interface has been superseded by Iterator. Although not deprecated,
it is used by the legacy classes such as Stack ,Vector and Properties etc.
Sr.No.Method & Description
1
boolean hasMoreElements( )
 it must return true while there are still more elements to extract, and false when all the elements have been enumerated.
2
Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.

Example

Following is an example showing usage of Enumeration.
import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

   public static void main(String args[]) {
      Enumeration days;
      Vector dayNames = new Vector();
      
      dayNames.add("Sunday");
      dayNames.add("Monday");
      dayNames.add("Tuesday");
      dayNames.add("Wednesday");
      dayNames.add("Thursday");
      dayNames.add("Friday");
      dayNames.add("Saturday");
      days = dayNames.elements();
      
      while (days.hasMoreElements()) {
         System.out.println(days.nextElement()); 
      }
   }
}
This will produce the following result −

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Iterator interface


  • Iterator interface provides the facility of iterating the elements in a forward direction only.
  • It is a universal iterator as we can apply it to any Collection object.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
No.MethodDescription
1public boolean hasNext()It returns true if the iterator has more elements otherwise it returns false.
2public Object next()It returns the element and moves the cursor pointer to the next element.
3public void remove()It removes the last elements returned by the iterator. It is less used.

Iterating Collection through Iterator interface

Let's see an example to traverse ArrayList elements using the Iterator interface.
  1. import java.util.*;  
  2. class ArrayList2{  
  3.  public static void main(String args[]){  
  4.   ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
  5.   list.add("Ravi");//Adding object in arraylist  
  6.   list.add("Vijay");  
  7.   list.add("Ravi");  
  8.   list.add("Ajay");  
  9.   //Traversing list through Iterator  
  10.   Iterator itr=list.iterator();  
  11.   while(itr.hasNext()){  
  12.    System.out.println(itr.next());  
  13.   }  
  14.  }  
  15. }  

       Ravi
       Vijay
       Ravi
       Ajay

Iterating Collection through the for-each loop

Let's see an example to traverse the ArrayList elements using the for-each loop
  1. import java.util.*;  
  2. class ArrayList3{  
  3.  public static void main(String args[]){  
  4.   ArrayList<String> al=new ArrayList<String>();  
  5.   al.add("Ravi");  
  6.   al.add("Vijay");  
  7.   al.add("Ravi");  
  8.   al.add("Ajay");  
  9.    //Traversing list through for-each loop  
  10.   for(String obj:al)  
  11.     System.out.println(obj);  
  12.  }  
  13. }  
       Ravi
       Vijay
       Ravi
       Ajay

Java ListIterator Interface

ListIterator Interface is used to traverse the element in a backward and forward direction.

Methods of Java ListIterator Interface:

MethodDescription
void add(E e)This method inserts the specified element into the list.
boolean hasNext()This method returns true if the list iterator has more elements while traversing the list in the forward direction.
E next()This method returns the next element in the list and advances the cursor position.
int nextIndex()This method returns the index of the element that would be returned by a subsequent call to next()
boolean hasPrevious()This method returns true if this list iterator has more elements while traversing the list in the reverse direction.
E previous()This method returns the previous element in the list and moves the cursor position backward.
E previousIndex()This method returns the index of the element that would be returned by a subsequent call to previous().
void remove()This method removes the last element from the list that was returned by next() or previous() methods
void set(E e)This method replaces the last element returned by next() or previous() methods with the specified element.

Example of ListIterator Interface

  1. import java.util.*;  
  2. public class ListIteratorExample1{  
  3. public static void main(String args[]){  
  4. List<String> al=new ArrayList<String>();    
  5.         al.add("Amit");    
  6.         al.add("Vijay");    
  7.         al.add("Kumar");    
  8.         al.add(1,"Sachin");    
  9.         ListIterator<String> itr=al.listIterator();    
  10.         System.out.println("Traversing elements in forward direction");    
  11.         while(itr.hasNext()){    
  12.               
  13.         System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());    
  14.         }    
  15.         System.out.println("Traversing elements in backward direction");    
  16.         while(itr.hasPrevious()){    
  17.           
  18.         System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());    
  19.         }    
  20. }  
  21. }  
Output:
Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

Iterating Collection through remaining ways

Let's see an example to traverse the ArrayList elements through other ways
  1. import java.util.*;  
  2. class ArrayList4{  
  3.  public static void main(String args[]){  
  4.     ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
  5.            list.add("Ravi");//Adding object in arraylist  
  6.            list.add("Vijay");  
  7.            list.add("Ravi");  
  8.            list.add("Ajay");  
  9.             
  10.            System.out.println("Traversing list through List Iterator:");  
  11.            //Here, element iterates in reverse order  
  12.               ListIterator<String> list1=list.listIterator(list.size());  
  13.               while(list1.hasPrevious())  
  14.               {  
  15.                   String str=list1.previous();  
  16.                   System.out.println(str);  
  17.               }  
  18.         System.out.println("Traversing list through for loop:");  
  19.            for(int i=0;i<list.size();i++)  
  20.            {  
  21.             System.out.println(list.get(i));     
  22.            }  
  23.               
  24.         System.out.println("Traversing list through forEach() method:");  
  25.         //The forEach() method is a new feature, introduced in Java 8.  
  26.             list.forEach(a->{ //Here, we are using lambda expression  
  27.                 System.out.println(a);  
  28.               });  
  29.                
  30.            
  31.  }  
  32. }  
Traversing list through List Iterator:
Ajay
Ravi
Vijay
Ravi
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay

Set Interface

Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the un ordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set.
Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
  1. Set<data-type> s1 = new HashSet<data-type>();  
  2. Set<data-type> s2 = new LinkedHashSet<data-type>();  
  3. Set<data-type> s3 = new TreeSet<data-type>();  

Java HashSet

Java HashSet class hierarchy
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • HashSet allows one null value.
  • HashSet is the best approach for search operations.
  • The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

HashSet class declaration

Let's see the declaration for java.util.HashSet class.
  1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable  

Constructors of Java HashSet class

SNConstructorDescription
1)HashSet()It is used to construct a default HashSet.
2)HashSet(int capacity)It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
3)HashSet(int capacity, float loadFactor)It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
4)HashSet(Collection<? extends E> c)It is used to initialize the hash set by using the elements of the collection c.

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
  1. import java.util.*;  
  2. class HashSet1{  
  3.  public static void main(String args[]){  
  4.   //Creating HashSet and adding elements  
  5.     HashSet<String> set=new HashSet();  
  6.            set.add("One");    
  7.            set.add("Two");    
  8.            set.add("Three");   
  9.            set.add("Four");  
  10.            set.add("Five");  
  11.            Iterator<String> i=set.iterator();  
  12.            while(i.hasNext())  
  13.            {  
  14.            System.out.println(i.next());  
  15.            }  
  16.  }  
  17. }  
Five
One
Four
Two
Three

Java HashSet example ignoring duplicate elements

In this example, we see that HashSet doesn't allow duplicate elements.
  1. import java.util.*;  
  2. class HashSet2{  
  3.  public static void main(String args[]){  
  4.   //Creating HashSet and adding elements  
  5.   HashSet<String> set=new HashSet<String>();  
  6.   set.add("Ravi");  
  7.   set.add("Vijay");  
  8.   set.add("Ravi");  
  9.   set.add("Ajay");  
  10.   //Traversing elements  
  11.   Iterator<String> itr=set.iterator();  
  12.   while(itr.hasNext()){  
  13.    System.out.println(itr.next());  
  14.   }  
  15.  }  
  16. }  
       Ajay
       Vijay
       Ravi

Java LinkedHashSet class

Java HashSet class hierarchy
Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
  • Java LinkedHashSet class contains unique elements only like HashSet.
  • Java LinkedHashSet class maintains insertion order.








LinkedHashSet class declaration

Let's see the declaration for java.util.LinkedHashSet class.
  1. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable  

Constructors of Java LinkedHashSet class

ConstructorDescription
HashSet()It is used to construct a default HashSet.
HashSet(Collection c)It is used to initialize the hash set by using the elements of the collection c.
LinkedHashSet(int capacity)It is used initialize the capacity of the linked hash set to the given integer value capacity.
LinkedHashSet(int capacity, float fillRatio)It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.

Java LinkedHashSet Example

Let's see a simple example of Java LinkedHashSet class. Here you can notice that the elements iterate in insertion order.
  1. import java.util.*;  
  2. class LinkedHashSet1{  
  3.  public static void main(String args[]){  
  4.  //Creating HashSet and adding elements  
  5.         LinkedHashSet<String> set=new LinkedHashSet();  
  6.                set.add("One");    
  7.                set.add("Two");    
  8.                set.add("Three");   
  9.                set.add("Four");  
  10.                set.add("Five");  
  11.                Iterator<String> i=set.iterator();  
  12.                while(i.hasNext())  
  13.                {  
  14.                System.out.println(i.next());  
  15.                }  
  16.  }  
  17. }  
One
Two
Three
Four
Five


Java TreeSet class

TreeSet class hierarchy
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
  • Java TreeSet class contains unique elements only like HashSet.
  • Java TreeSet class access and retrieval times are quiet fast.
  • Java TreeSet class doesn't allow null element.
  • Java TreeSet class maintains ascending order.






TreeSet class declaration

Let's see the declaration for java.util.TreeSet class.
  1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable  

Constructors of Java TreeSet class

ConstructorDescription
TreeSet()It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set.
TreeSet(Collection<? extends E> c)It is used to build a new tree set that contains the elements of the collection c.
TreeSet(Comparator<? super E> comparator)It is used to construct an empty tree set that will be sorted according to given comparator.
TreeSet(SortedSet<E> s)It is used to build a TreeSet that contains the elements of the given SortedSet.

Methods of Java TreeSet class

MethodDescription
boolean add(E e)It is used to add the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c)It is used to add all of the elements in the specified collection to this set.
E ceiling(E e)It returns the equal or closest greatest element of the specified element from the set, or null there is no such element.
Comparator<? super E> comparator()It returns comparator that arranged elements in order.
Iterator descendingIterator()It is used iterate the elements in descending order.
NavigableSet descendingSet()It returns the elements in reverse order.
E floor(E e)It returns the equal or closest least element of the specified element from the set, or null there is no such element.
SortedSet headSet(E toElement)It returns the group of elements that are less than the specified element.
NavigableSet headSet(E toElement, boolean inclusive)It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element.
E higher(E e)It returns the closest greatest element of the specified element from the set, or null there is no such element.
Iterator iterator()It is used to iterate the elements in ascending order.
E lower(E e)It returns the closest least element of the specified element from the set, or null there is no such element.
E pollFirst()It is used to retrieve and remove the lowest(first) element.
E pollLast()It is used to retrieve and remove the highest(last) element.
Spliterator spliterator()It is used to create a late-binding and fail-fast spliterator over the elements.
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)It returns a set of elements that lie between the given range.
SortedSet subSet(E fromElement, E toElement))It returns a set of elements that lie between the given range which includes fromElement and excludes toElement.
SortedSet tailSet(E fromElement)It returns a set of elements that are greater than or equal to the specified element.
NavigableSet tailSet(E fromElement, boolean inclusive)It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element.
boolean contains(Object o)It returns true if this set contains the specified element.
boolean isEmpty()It returns true if this set contains no elements.
boolean remove(Object o)It is used to remove the specified element from this set if it is present.
void clear()It is used to remove all of the elements from this set.
Object clone()It returns a shallow copy of this TreeSet instance.
E first()It returns the first (lowest) element currently in this sorted set.
E last()It returns the last (highest) element currently in this sorted set.
int size()It returns the number of elements in this set.

Java TreeSet Examples

Java TreeSet Example 1:

Let's see a simple example of Java TreeSet.
  1. import java.util.*;  
  2. class TreeSet1{  
  3.  public static void main(String args[]){  
  4.   //Creating and adding elements  
  5.   TreeSet<String> al=new TreeSet<String>();  
  6.   al.add("Ravi");  
  7.   al.add("Vijay");  
  8.   al.add("Ravi");  
  9.   al.add("Ajay");  
  10.   //Traversing elements  
  11.   Iterator<String> itr=al.iterator();  
  12.   while(itr.hasNext()){  
  13.    System.out.println(itr.next());  
  14.   }  
  15.  }  
  16. }  
Test it Now
Output:
Ajay
Ravi
Vijay

Java TreeSet Example 2:

Let's see an example of traversing elements in descending order.
  1. import java.util.*;  
  2. class TreeSet2{  
  3.  public static void main(String args[]){  
  4.  TreeSet<String> set=new TreeSet<String>();  
  5.          set.add("Ravi");  
  6.          set.add("Vijay");  
  7.          set.add("Ajay");  
  8.          System.out.println("Traversing element through Iterator in descending order");  
  9.          Iterator i=set.descendingIterator();  
  10.          while(i.hasNext())  
  11.          {  
  12.              System.out.println(i.next());  
  13.          }  
  14.            
  15.  }  
  16. }  
Test it Now
Output:
Traversing element through Iterator in descending order
Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay

Java TreeSet Example 3:

Let's see an example to retrieve and remove the highest and lowest Value.
  1. import java.util.*;  
  2. class TreeSet3{  
  3.  public static void main(String args[]){  
  4.  TreeSet<Integer> set=new TreeSet<Integer>();  
  5.          set.add(24);  
  6.          set.add(66);  
  7.          set.add(12);  
  8.          set.add(15);  
  9.          System.out.println("Highest Value: "+set.pollFirst());  
  10.          System.out.println("Lowest Value: "+set.pollLast());  
  11.  }  
  12. }  
Output:
Highest Value: 12
Lowest Value: 66

Java TreeSet Example 4:

In this example, we perform various NavigableSet operations.
  1. import java.util.*;  
  2. class TreeSet4{  
  3.  public static void main(String args[]){  
  4.   TreeSet<String> set=new TreeSet<String>();  
  5.          set.add("A");  
  6.          set.add("B");  
  7.          set.add("C");  
  8.          set.add("D");  
  9.          set.add("E");  
  10.          System.out.println("Initial Set: "+set);  
  11.            
  12.          System.out.println("Reverse Set: "+set.descendingSet());  
  13.            
  14.          System.out.println("Head Set: "+set.headSet("C"true));  
  15.           
  16.          System.out.println("SubSet: "+set.subSet("A"false"E"true));  
  17.            
  18.          System.out.println("TailSet: "+set.tailSet("C"false));  
  19.  }  
  20. }  
Output:
Initial Set: [A, B, C, D, E]
Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

Java TreeSet Example 4:

In this example, we perform various SortedSetSet operations.
  1. import java.util.*;  
  2. class TreeSet4{  
  3.  public static void main(String args[]){  
  4.   TreeSet<String> set=new TreeSet<String>();  
  5.          set.add("A");  
  6.          set.add("B");  
  7.          set.add("C");  
  8.          set.add("D");  
  9.          set.add("E");  
  10.            
  11.          System.out.println("Intial Set: "+set);  
  12.            
  13.          System.out.println("Head Set: "+set.headSet("C"));  
  14.           
  15.          System.out.println("SubSet: "+set.subSet("A""E"));  
  16.            
  17.          System.out.println("TailSet: "+set.tailSet("C"));  
  18.  }  
  19. }  
Output:
Intial Set: [A, B, C, D, E]
Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]



Comments

Popular posts from this blog

C Programming

C Programming: ----------------- C is a general purpose programming language founded by Dennis Ritche in 1972 at Bell labs. Language: ------- Langue is a vocabulary and set of  gamer rules to community human in the world. 1)Learn alphabets(a-z) 2)Form words(i,we,he she,they ,the ete) 3)Form sentence by set of gramer rules. 4)Paragraph. ex: I go to office everyday at 10 am. Programming language: Programming language is a vocabulary and set of gramer rules to instruct the computer to perform various task. 1)learn alphabets,numbers,special symbols(a-z,0-9,@,$,^) 2)int a,b,c; 3)c=a+b; 4)program c can be defines as follows: 1.mother language.  Most of the compilers,JVM's and kernels are written in c.  Most of the languages follow c syntax. 2.Procedure oriented language.  A procedure is know as function,methods,routine or sub routine.A procedure language specifies a series of steps for the program to perform tasks. 3.Structured language. Struc...

Core Java part2

Java catch multiple exceptions: A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. At a time only one exception occurs and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. Example : In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked. public class MultipleCatchBlock4 {          public static void main(String[] args) {                         try{                     String s=null;              ...