Introduction

The Java programming language has many features that help coders write programs efficiently. Java Collection Framework is one such functionality offered by JDK 1.2 that allows users to use the group of objects. Java collection framework provides many methods that enable coders to write efficient code to improve code implementation and reusability. Read this article to learn more about the Java collection framework and how to use it.

  1. What is Framework in Java Collection?
  2. Java Collections Hierarchy
  3. Why are Collections Used in Java Code?
  4. Types of Collections in Java
  5. Collector Framework Methods
  6. Advantages of Collection Framework

1) What is Framework in Java Collection?

The framework can be described as code classes and interfaces available for use. A coder need not create a new framework every time a new feature needs to be implemented. Frameworks and collection of classes are available as part of optimal design in object-oriented architecture such that all classes perform similar tasks. The collection framework is one such framework in the Java programming language. A collection is a group of objects that can be represented as a single unit. The Java collection framework was introduced in JDK 1.2, and it is a set of collection classes. The two primary interfaces of the collection framework are the collection interface and the map interface. Java.util. 

2) Java Collections Hierarchy

The image below illustrates the Java collection hierarchy as defined in java.util package. The interfaces and classes of the Java collections framework are described in the article below. The hierarchy collection example in Java has also been explained. 

Source: https://www.jigsawacademy.com/blogs/java/collection-framework-in-java/

3) Why are Collections Used in Java Code? 

Before the collection framework was introduced in JDK 1.2, grouping objects in Java, such as vectors, arrays, and hashtables, performed the same tasks. But the issue with these collection objects was the lack of a standard interface. Moreover, all these collections accomplish the same task using different methods. However, it was difficult for a user to remember all the methods, constructors, and syntax. Thus, a typical Java collection framework was introduced.

4) Types of Collections in Java

The collection interface consists of the interfaces inside the collection framework implemented by all the classes present in the collection framework. The collection interface defines the methods that the collection framework can use. We know that interfaces contain the declaration of functions implemented by the classes. The collection framework does the same. The interfaces in the collection framework declare the methods. The classes in the collection framework implement these interfaces. Also, the classes define the methods to ensure the use of techniques. In other words, the collection interfaces form the foundation for the collection framework. Below are the collection interfaces:

  1. Iterable Interface

The iterable interface is the root interface extended by the collection interface. Therefore, all the interfaces and classes inherit from the iterable interface. This interface helps provide the iterator to the collection. It has an abstract method called iterator(). The syntax is as below:

Iterator iterator();

  1. List Interface

List interface is like the child interface of the collection interface. It makes use of the list data type in which the objects are stored. List interface also allows storing duplicate data in the list. Different classes that implement the list interface include Vector, ArrayList, Stack, LinkedList. The subclasses implement the list interface, so the list object can be instantiated using subclasses.

Below is the syntax to instantiate the subclasses mentioned here:

List <Datatype> obj1 = new ArrayList();

List <Datatype> obj2 = new LinkedList();

List <Datatype> obj3 = new Stack();

List <Datatype> obj4 = new Vector();

<Datatype> is the data type of the collection object in Java obj1, obj2, obj3, and obj4.

The classes given below implement the list interface:

i) ArrayList: The class ArrayList implements the list interface and provides the feature of a dynamic array in Java. This type of array is slow compared to the usual array, but it is quite useful when extensive array manipulation is required. The ArrayList size changes as the elements are removed or added to the list. It cannot be used for primitive data types and needs wrapper class in such cases.

Below is the code snippet that illustrates the use of an ArrayList:

Import java.util.*;

Class CollectionExample1

{

           Public static void main(String args[])

           {

                       //Instantiate ArrayList

                       ArrayList<String> Subject = new ArrayList<String>();

                       //Adding subjects in the ArrayList

                       Subject.add(“English”);

                       Subject.add(“Mathematics”);

                       Subject.add(“Science”);

                       Subject.add(“Hindi”);

                       //Using iterator to traverse the ArrayList

                       Iterator i1 = Subject.iterator();

                       While(i1.hasNext())

                       {

                                   System.out.println(i1.next());

                       }

           }

}

Output:

English

Mathematics

Science

Hindi

ii) LinkedList The LinkedList class implements the list interface. It ensures faster manipulation as it does not involve shifting. The elements are stored internally as a doubly-linked list. It can also store duplicate elements.

Below is the code snippet that illustrates the use of LinkedList:

Import java.util.*;

Class CollectionExample2

{

           Public static void main(String args[])

           {

                       //Instantiate LinkedList

                       LinkedList<String> EmpName = new LinkedList<String>();

                       //Adding Names in the LinkedList

                       EmpName.add(“Peter”);

                       EmpName.add(“Mary”);

                       EmpName.add(“John”);

                       EmpName.add(“Rachael”);

                       //Using iterator to traverse the LinkedList

                       Iterator<String> i1 = EmpName.iterator();

                       While(i1.hasNext())

                       {

                                   System.out.println(i1.next());

                       }

           }

}

Output:

Peter

Mary

John

Rachael

iii) Vector: Vector is similar to ArrayList and stores the elements in a dynamic array. It gets synchronized, unlike ArrayList, and some methods of the vector are not even part of the collection interface.

Below is the code snippet that illustrates a vector:

Import java.util.*;

Class CollectionExample3

{

           Public static void main(String args[])

           {

                       //Instantiate Vector

                       Vector<String> Subject = new Vector<String>();

                       //Adding subjects in the Vector

                       Subject.add(“English”);

                       Subject.add(“Mathematics”);

                       Subject.add(“Science”);

                       Subject.add(“Hindi”);

                       //Using iterator to traverse the Vector

                       Iterator i1 = Subject.iterator();

                       While(i1.hasNext())

                       {

                                   System.out.println(i1.next());

                       }

           }

}

Output:

English

Mathematics

Science

Hindi

iv) Stack: A stack is the collection class, a subclass of vector class that implements the list interface. This class contains the methods defined or implemented in the vector class. Apart from the methods of vector class, it has processes, such as boolean push(), boolean push (Object o), and boolean peek().

Below is the code snippet that illustrates stack usage:

Import java.util.*;

Class CollectionExample4

{

           Public static void main(String args[])

           {

                        //Instantiate Stack

                       Stack<String> Subject = new Stack<String>();

                       //Adding subjects in the Stack

                       Subject.push(“English”);

                       Subject.push(“Mathematics”);

                       Subject.push(“Science”);

                       Subject.push(“Hindi”);

                       // Remove the last element from the Stack

                       Subject.pop();

                       //Using iterator to traverse the Stack

                       Iterator i1 = Subject.iterator();

                       While(i1.hasNext())

                       {

                                   System.out.println(i1.next());

                       }

           }

}

Output:

English

Mathematics

Science

3. Queue Interface

The queue interface is the list that stores the elements. It works like a normal queue, i.e., First In First Out (FIFO). In this interface, the order of storing the elements matter. For example, in the ticketing system, a person higher on the waiting list gets ticket confirmation first on cancellation of a reservation. The queue interface has classes, such as Deque, Priority Queue, and ArrayDeque. All these classes implement the queue interface. Below is the syntax to instantiate the queue interface:

Queue <Data Type> obj1 = new PriorityQueue();

Queue <Data Type> obj2 = new ArrayDeque();

Obj1 and obj2 are the data types of objects obj1 and obj2.

Below are some classes that implement the Queue interface:

i) Priority Queue: The queue interface is implemented by the PriorityQueue class—the class stores the objects or the elements that need to be processed according to priorities. The class does not allow the queue to store null values.

Below is the code illustrating PriorityQueue:

Import java.util.*;

Class CollectionExample5

{

           Public static void main(String args[])

           {

                       //Instantiate PriorityQueue

                       PriorityQueue<String> Subject = new PriorityQueue<String>();

                       //Adding subjects in the PriorityQueue

                       Subject.add(“English”);

                       Subject.add(“Mathematics”);

                       Subject.add(“Science”);

                       Subject.add(“Hindi”);

                       System.out.println(Subject.element() + “ is the head of the queue”);

                       System.out.println(queue.peek()+ “ is the head of the queue”);

                       Subject.remove();

                       Subject.poll();

System. Out.println(“After removing the elements, the queue has elements”)

//Using iterator

                       Iterator i1 = Subject.iterator();

                       While(i1.hasNext())

                       {

                                   System.out.println(i1.next());

                       }

           }

}

Output:

English is the head of the queue.

English is the head of the queue.

After removing the elements, the queue has elements.

Science

Hindi

4. Deque Interface

The queue interface is extended by the deque interface. Unlike the queue interface, elements can be added or removed from this list from both sides. This is the reason it is called the deque interface. The deque interface is also called the double-ended queue. It allows operations to be performed on both sides of the queue. Below is the syntax to instantiate the deque interface:

Dequ1 <Data Type> obj = new ArrayDeque();

i) ArrayDeque

ArrayDeque is the class that implements the deque interface. It allows the use of deque. ArrayDeque allows you to add a new element or remove the existing element from the array on both sides. ArrayDeque works faster than stack and ArrayList. It has no restriction on capacity.

Below is the code illustrating ArrayDeque

Import java.util.*;

Public class CollectionExample6

{

           //Create ArrayDeque

           Deque<String> Subject = new ArrayDeque<String>);

           Subject.add(“English”);

           Subject.add(“Mathematics”)’

           Subject.add(“Hindi”);

           // Traverse the elements of ArrayDeque

           for(String s1 : Subject)

           {

                       System.out.println(s1);

           }

}

Output:

English

Mathematics

Hindi

5. Set interface

The set interface is a Java interface that does not store elements in order and does not store duplicate elements. It is present in the java.util package. The collection interface is extended by the set interface. The set interface is implemented by classes, such as TreeSet, HashSet, and LinkedHashSet. Below is the syntax to instantiate the classes that implement the set interface:

Set <Data Type> obj1 = new HashSet <Data Type>();

Set <Data Type> obj2 = new LinkedHashSet <Data Type>();

Set <Data Type> obj3 = new TreeSet <Data Type>();

Here, Data Type refers to the data type of the instances obj1, obj2, and obj3.

i) HashSet

HashSet is the class that implements the set Interface. The class also represents the collection, where hash tables and hashing are used for storage. HashSet allows you to store unique elements only.

Below is the code illustrating a HashSet

Import java.util.*;

Public class CollectionExample7

{

           //Create Hashset

           HashSet<String> Subject = new HashSet<String>();

           Subject.add(“English”);

           Subject.add(“Mathematics”)’

           Subject.add(“Hindi”);

           // Traverse the elements of HashSet

           Iterator<String> i1 = set.iterator();

           While(i1.hasNext())

           {

                       System.out.println(i1.next());

           }

}

Output:

English

Mathematics

Hindi

ii) LinkedHashSet

LinkedHashSet is another class that implements the set interface in Java and extends the HashSet class. A LinkedHashSet class allows storing unique elements and null elements, and it also maintains the insertion order.

Below is the code illustrating a LinkedHashSet

Import java.util.*;

Public class CollectionExample8

{

           //Create LinkedHashset

           LinkedHashSet<String> Subject = new LinkedHashSet<String>();

           Subject.add(“English”);

           Subject.add(“Mathematics”)’

           Subject.add(“Hindi”);

           // Traverse the elements of LinkedHashSet

           Iterator<String> i1 = set.iterator();

           While(i1.hasNext())

           {

                       System.out.println(i1.next());

           }

}

Output:

English

Mathematics

Hindi

6. SortedSet Interface

SortedSet is an interface in Java that follows an order while storing elements. The elements are stored in increasing order in a SortedSet. Also, it is a method to store elements in ascending order, preventing them from being arranged in their natural order.

Below is the syntax to instantiate the SortedSet interface:

SortedSet <DataType> obj = new TreeSet();

Data Type is the data type of instance obj, and a TreeSet is a class that implements the SortedSet interface.

TreeSet

TreeSet is a Java collection class that implements the SortedSet interface. TreeSet class stores the elements in the tree structure. TreeSet allows only unique elements to be stored in increasing order. The TreeSet class is a quick method to access the elements stored in it.

Below is the code illustrating a TreeSet

Import java.util.*;

Public class CollectionExample8

{

           //Create TreeSet

           TreeSet<String> Subject = new TreeSet<String>();

           Subject.add(“English”);

           Subject.add(“Mathematics”)’

           Subject.add(“Hindi”);

           // Traverse the elements of TreeSet

           Iterator<String> i1 = set.iterator();

           While(i1.hasNext())

           {

                       System.out.println(i1.next());

           }

}

Output:

English

Hindi

Mathematics

5) Collector Framework Methods

Below is the list of function/methods available in a collector framework:

MethodDescription
Public Boolean addAll(Collection<? extends E> c)This method is used to insert the elements of a particular collection in the invoking collection.
Public Boolean add (E e)It can be used to insert the element in the collection.
Public Boolean remove All (collection<?>c)It can be used to remove the entire specified collection elements from the invoking collection.
Public Boolean remove (Object element)Programmers use this method to delete an element from the collection.
Public Boolean retain All (collection<?>c)This method is used to remove the invoking collection elements except for a particular collection.
Default Boolean remove (predicate<?super E>filter)Programmers use this method to delete the entire collection elements that satisfy a particular predicate.
Public Void Clear ()This method deletes the entire elements available in the collection.
Public Boolean Contains All (Collection<?>c)This method can be used to find a particular collection in the collection.
Public int Size ()This method returns the entire elements available in the collection.
Public Boolean contains (Object element)Programmers use this code to find out the element.
Public <T> T[] toArray (T[] a)This method is used to convert the collection into an array.
Public Iterator Iterator ()This method returns the iterator.
Public Boolean is Empty()The method checks if the collection is empty.
Public object [] to Array ()It is used to convert the collection into an array.
Default Stream <E> ParallelStream ()This method is used to return a parallel stream with a collection as a source of it.
Default Spliterator <E> Spliterator ()This method creates the spliterator over the particular collection elements.
Public int hashCode ()This method returns the collection hash code number.
Default Stream <E> stream ()This method returns a stream with a collection as its source.
Public Boolean equal (object element)This method helps match two collections.

6) Advantages of Collection Framework

Given below are the advantages of the Java collection framework:

  • Abstraction, the object-oriented framework’s basic concept, is wholly implemented as part of the collection framework. It helps coders use the collection framework in the best way possible without worrying about the collection architecture.
  • The collection framework improves performance by implementing useful algorithms and data structures, so the coder does not need to find the best implementable code on the given data structure. Instead, the coder can use the implementation to get the best performing code.
  • API uses classes such as LinkedList, ArrayList, vector, and interfaces such as collection, list, map, set.
  • The use of the collections framework enhances the interoperability and reusability of code.

Conclusion

The Java collection framework is useful for coders to write efficient code in Java. In this article, the interfaces and classes of the Java collection framework have been explained with examples. We hope the article helped you understand the concept well. You can find similar articles on Jigsaw Academy to learn more about the different concepts in Java and other technical topics. You can also opt for the Master Certificate in Full Stack Development to learn full-fledged Java.

Also Read

SHARE