Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy.
There are different type collections
1. ArrayList
2. LinkedList
3. Vector
4. HashSet
5. LinkedHashSet
6. TreeSet
7. HashMap
8. TreeMap
9. LinkedHashMap
10. Hashtable
11. Iterator and ListIterator
12. Comparable and Comparator
Collections List
A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. Elements can be inserted or accessed by their position in the list, using a zero-based index.
ArrayList
Here is the list of all the tutorials published on the ArrayList.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
| No |
Method |
Description |
| 1 |
public boolean add(E e) |
It is used to insert an element in this collection. |
| 2 |
public boolean addAll(Collection extends E> c) |
It is used to insert the specified collection elements in the invoking collection.
|
| 3 |
public boolean remove(Object element) |
It is used to delete an element from the collection. |
| 4 |
public boolean removeAll(Collection> c) |
It is used to delete all the elements of the specified collection from the invoking collection. |
| 5 |
default boolean removeIf(Predicate super E> filter) |
It is used to delete all the elements of the collection that satisfy the specified predicate. |
| 6 |
public boolean retainAll(Collection> c) |
It is used to delete all the elements of invoking collection except the specified collection. |
| 7 |
public int size() |
It returns the total number of elements in the collection. |
| 8 |
public void clear() |
It removes the total number of elements from the collection. |
| 9 |
public boolean contains(Object element) |
It is used to search an element. |
| 10 |
public boolean containsAll(Collection> c) |
It is used to search the specified collection in the collection. |
| 11 |
public Iterator iterator() |
It returns an iterator. |
| 12 |
public Object[] toArray() |
It converts collection into array. |
| 13 |
public T[] toArray(T[] a) |
It converts collection into array. Here, the runtime type of the returned array is that of the specified array. |
| 14 |
public boolean isEmpty() |
It checks if collection is empty. |
| 15 |
default Stream parallelStream() |
It returns a possibly parallel Stream with the collection as its source. |
| 16 |
default Stream stream() |
It returns a sequential Stream with the collection as its source. |
| 17 |
default Spliterator spliterator() |
It generates a Spliterator over the specified elements in the collection. |
| 18 |
public boolean equals(Object element) |
It matches two collections. |
| 19 |
public int hashCode() |
It returns the hash code number of the collection. |
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
| No. |
Method |
Description |
| 1 |
public boolean hasNext() |
It returns true if the iterator has more elements otherwise it returns false. |
| 2 |
public Object next() |
It returns the element and moves the cursor pointer to the next element. |
| 3 |
public void remove() |
It removes the last elements returned by the iterator. It is less used. |
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
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. In other words, we can say that the Collection interface builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
| List list1= new ArrayList(); |
| List list2 = new LinkedList(); |
| List list3 = new Vector(); |
| List list4 = new Stack(); |
There are various methods in List interface that can be used to insert, delete, and access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the following example.
| import java.util.*; |
| class ArrayListTest{ |
| public static void main(String args[]){ |
| ArrayList list=new ArrayList();//Creating arraylist |
| list.add("Rahul");//Adding object in arraylist |
| list.add("Ajay"); |
| list.add("Gaurav"); |
| list.add("Virat"); |
| //Traversing list through Iterator |
| Iterator itr=list.iterator(); |
| while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| } |
| } |
| Output: |
| Rahul |
| Ajay |
| Gaurav |
| Virat |
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
| import java.util.*; |
| public class LinkedListTest{ |
| public static void main(String args[]){ |
| LinkedList al=new LinkedList(); |
| al.add("Rohan"); |
| al.add("Prem"); |
| al.add("Sagar"); |
| al.add("Rohan"); |
| Iterator itr=al.iterator(); |
| while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| } |
| } |
| Output: |
| Rohan |
| Prem |
| Akash |
| Rohan |
Vector
A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This is identical to ArrayList in terms of implementation. However, the primary difference between a vector and an ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized. Let’s understand the Vector with an example:
| import java.util.*; |
| public class VectorTest{ |
| public static void main(String args[]){ |
| Vector v=new Vector(); |
| v.add("Karan"); |
| v.add("Suraj"); | i
| v.add("Rohit"); | h
| v.add("Prem"); |
| Iterator itr=v.iterator(); |
| while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| } |
| } |
| Output: |
| Karan |
| Suraj |
| Rohit |
| Prem |
Stack
Stack class models and implements the Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be referred to as the subclass of Vector. Let’s understand the stack with an example:
| import java.util.*; |
| public class StackTest |
| public static void main(String args[]){ |
| Stack stack = new Stack(); |
| stack.push("Karan"); |
| stack.push("Suraj"); |
| stack.push("Rohit"); |
| stack.push("Prem"); |
| stack.push("Rohan"); |
| stack.pop(); |
| Iterator itr=stack.iterator(); |
while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| } |
| } |
| Output: |
| Karan |
| Suraj |
| Rohit |
Queue Interface
a queue interface maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter. For example, whenever we try to book a ticket, the tickets are sold at the first come first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There are various classes like PriorityQueue, Deque, ArrayDeque, etc. Since all these subclasses implement the queue, we can instantiate a queue object with any of these classes.
Queue interface can be instantiated as:
| Queue q1 = new PriorityQueue(); |
| Queue q2 = new ArrayDeque(); |
There are various classes that implement the Queue interface, some of them are given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.
For example.
| import java.util.*; |
| public class PriorityQueueTest{ |
| public static void main(String args[]){ |
| PriorityQueue queue=new PriorityQueue(); |
| queue.add("Rohit"); |
| queue.add("Raj"); |
| queue.add("Prem"); |
| queue.add("Suraj"); |
| System.out.println("head:"+queue.element()); |
| System.out.println("head:"+queue.peek()); |
| System.out.println("iterating the queue elements:"); |
| Iterator itr=queue.iterator(); |
| while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| queue.remove(); |
| queue.poll(); |
| System.out.println("after removing two elements:"); |
| Iterator itr2=queue.iterator(); |
| while(itr2.hasNext()){ |
| System.out.println(itr2.next()); |
| } |
| } |
| } |
| Output: |
| head:Rohit |
| head:Rohit |
| iterating the queue elements: |
| Rohit |
| Suraj |
| Prem |
| Raj |
| after removing two elements: |
| Suraj |
| Raj |
|
Deque Interface
This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue, is a data structure where we can add and remove the elements from both the ends of the queue. This interface extends the queue interface. The class which implements this interface is ArrayDeque. Since this class implements the deque, we can instantiate a deque object with this class. For example
| Deque d = new ArrayDeque(); |
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
| import java.util.*; |
| public class ArrayDequeTest{ |
| public static void main(String[] args) { |
| Deque deque = new ArrayDeque(); |
| deque.add("Rahul"); |
| deque.add("Karan"); |
| deque.add("Ajay"); |
| //Traversing elements |
| for (String str : deque) { |
| System.out.println(str); |
| } |
| } |
| } |
| Output: |
| Rahul |
| Karan |
| Ajay |
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered 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:
| Set s1 = new HashSet(); |
| Set s2 = new LinkedHashSet(); |
| Set s3 = new TreeSet(); |
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Consider the following example.
| import java.util.*; |
| public class HashSetTest{ |
| public static void main(String args[]){ |
| //Creating HashSet and adding elements |
| HashSet set=new HashSet(); |
| set.add("Prem"); |
| set.add("Raj"); |
| set.add("Prem"); |
| set.add("Rohit"); |
| //Traversing elements |
| Iterator itr=set.iterator(); |
| while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| } |
| } |
| Output: |
| Prem |
| Raj |
| Rohit |
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.
example.
| import java.util.*; |
| public class LinkedHashSetTest{ |
| public static void main(String args[]){ |
| LinkedHashSet set=new LinkedHashSet(); |
| set.add("Rohan"); |
| set.add("Raj"); |
| set.add("Gaurav"); |
| set.add("Prem"); |
| set.add("Raj"); |
| Output: |
| Rohan |
| Raj |
| Gaurav |
| Prem |
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional methods that inhibit the natural ordering of the elements.
The SortedSet can be instantiated as:
| SortedSet set = new TreeSet(); |
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.r
Consider the following example:
| import java.util.*; |
| public class TreeSetTest{ |
| //Creating and adding elements |
| TreeSet set=new TreeSet(); |
| set.add("Rohit"); |
| set.add("Prem"); |
| set.add("Raj"); |
| set.add("Rohit"); |
| //traversing elements |
| Iterator itr=set.iterator(); |
| while(itr.hasNext()){ |
| System.out.println(itr.next()); |
| } |
| } |
| } |
| Output: |
| Prem |
| Raj |
| Rohit |
ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array,but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and 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 ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
| public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable |
Constructors of ArrayList
| Constructor |
Description |
| 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. |
Methods of ArrayList
| Method |
Description |
| void add(int index, E element) |
It is used to insert the specified element at the specified position in a list. |
| boolean add(E e) |
It is used to append the specified element at the end of a list. |
| boolean addAll(Collection extends E> c) |
It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. |
| 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. |
| void clear() |
It is used to remove all of the elements from this list. |
| void ensureCapacity(int requiredCapacity) |
It is used to enhance the capacity of an ArrayList instance. |
| E get(int index) |
It is used to fetch the element from the particular position of the list. |
| boolean isEmpty() |
It returns true if the list is empty, otherwise false. |
| 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. |
| Object[] toArray() |
It is used to return an array containing all of the elements in this list in the correct order. |
| T[] toArray(T[] a) |
It is used to return an array containing all of the elements in this list in the correct order. |
| Object clone() |
It is used to return a shallow copy of an ArrayList. |
| boolean contains(Object o) |
It returns true if the list contains the specified 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. |
| boolean remove(Object o) |
It is used to remove the first occurrence of the specified element. |
| boolean removeAll(Collection> c) |
It is used to remove all the elements from the list. |
| boolean removeIf(Predicate super E> filter) |
It is used to remove all the elements from the list that satisfies the given predicate. |
| protected void removeRange(int fromIndex, int toIndex) |
It is used to remove all the elements lies within the given range. |
| void replaceAll(UnaryOperator operator) |
It is used to replace all the elements from the list with the specified element. |
| void retainAll(Collection> c) |
It is used to retain all the elements in the list that are present in the specified collection. |
| 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. |
| Spliterator spliterator() |
It is used to create spliterator over the elements in a list. |
| List subList(int fromIndex, int toIndex) |
It is used to fetch all the elements lies within the given range. |
|
|
| int size() |
It is used to return the number of elements present in the list. |
| void trimToSize() |
It is used to trim the capacity of this ArrayList instance to be the list's current size. |
| Iterator() |
|
| listIterator() |
|
ArrayList Example
| import java.util.*; |
| public class ArrayListTest{{ |
| public static void main(String args[]){ |
| ArrayList list=new ArrayList();//Creating arraylist |
| list.add("Apple");//Adding object in arraylist |
| list.add("Sony"); |
| list.add("Samsung"); |
| list.add("Nokia"); |
| //Printing the arraylist object |
| System.out.println(list); |
| } |
| } |
| } |
| Output: |
| [Apple,Sony,Samsung,Nokia] |
|
|
|
Iterating ArrayList using Iterator
| import java.util.*; |
| public class ArrayListTest{{ |
| public static void main(String args[]){ |
| ArrayList list=new ArrayList();//Creating arraylist |
| list.add("Apple");//Adding object in arraylist |
| list.add("Sony"); |
| list.add("Samsung"); |
| list.add("Nokia"); |
| //Traversing list through Iterator |
| Iterator itr=list.iterator();//getting the Iterator |
| while(itr.hasNext());{//check if iterator has the elements |
| System.out.println(itr.next());//printing the element and move to next |
| } |
| } |
| } |
| Output: |
| Apple |
| Sony |
| Samsung |
| Nokia |
Sorting ArrayList
The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
| import java.util.*; |
| public class ArrayListTest{{ |
| public static void main(String args[]){ |
| ArrayList list1=new ArrayList();//Creating list of mobile brand |
| list1.add("Apple");//Adding object in arraylist |
| list1.add("Sony"); |
| list1.add("Samsung"); |
| list1.add("Nokia"); |
| //sorting the list |
| collection.sort(list1); |
| //Traversing list through the for-each loop |
| for(String fruit:list1) |
| System.out.println(fruit); |
| System.out.println("Sorting numbers..."); |
| //Creating a list of numbers |
| List list2=new ArrayList(); |
| list2.add(43); |
| list2.add(32); |
| list2.add(51); |
| list2.add(11); |
| list2.add(28); |
| //Sorting the list |
| Collections.sort(list2); |
| //Traversing list through the for-each loop |
| for(Integer number:list2) |
| System.out.println(number); |
| } |
| } |
| Output: |
| Apple |
| Nokia |
| Samsung |
| Sony |
| } |
| } |
| 11 |
| 28 |
| 32 |
| 43 |
| 51 |