Collection in Java
Collection in Java
Java collections refer to a collection of individual objects that are represented as a single
unit. You can perform all operations such as searching, sorting, insertion, manipulation,
deletion, etc., on Java collections just like you do it on data.
Interfaces: Interface in Java refers to the abstract data types. They allow Java collections to
be manipulated independently from the details of their representation. Also, they form a
hierarchy in object-oriented programming languages.
Classes: Classes in Java are the implementation of the collection interface. It basically refers
to the data structures that are used again and again.
Algorithm: Algorithm refers to the methods which are used to perform operations such as
searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can say
perform different implementations of the Java collection interface.
So why do you think we need Java collections? The Java collection framework provides the
developers to access pre-packaged data structures as well as algorithms to manipulate data.
In the above image, blue part refers to the different interfaces and the yellow
part defines the class. Now, let us understand these components in detail.
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.
This interface contains various methods which can be directly used by all the collections
which implement this interface. They are:
Method Description
This method adds all the elements in the given collection to this
addAll(Collection c) collection.
clear() This method removes all of the elements from this collection.
contains(Object o) This method returns true if the collection contains the specified element.
containsAll(Collection This method returns true if the collection contains all of the elements in
c) the given collection.
This method compares the specified object with this collection for
equals(Object o) equality.
hashCode() This method is used to return the hash code value for this collection.
iterator() This method returns an iterator over the elements in this collection.
max() This method is used to return the maximum value present in the
collection.
This method is used to remove the given object from the collection. If
there are duplicate values, then this method removes the first occurrence
remove(Object o) of the object.
Method Description
removeAll(Collection This method is used to remove all the objects mentioned in the given
c) collection from the collection.
This method is used to retain only the elements in this collection that are
retainAll(Collection c) contained in the specified collection.
size() This method is used to return the number of elements in the collection.
Iterator interface:
Iterator is an interface that iterates the elements. It is used to traverse the list and modify
the elements. Iterator interface has three methods which are mentioned below:
1. public boolean hasNext() – This method returns true if the iterator has more elements.
2. public object next() – It returns the element and moves the cursor pointer to the next
element.
3. public void remove() – This method removes the last elements returned by the
iterator.
There are three components that extend the collection interface i.e List, Queue and Sets.
Let’s learn about them in detail:
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.
Iterator<T> iterator()
Array list: ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is increased dynamically
if the elements are added more than the initial size.
Syntax:
ArrayList object = new ArrayList ();
ArrayList example:
import java.util.*;
class ArrayListExample
{
public static void main(String args[])
{
ArrayList al=new ArrayList(); // creating array list
al.add("Jack"); // adding elements
al.add("Tyler");
Iterator itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
In the above code, it will return the names that we have added using add() method i.e:
Jack
Tyler
Linked List: Linked List is a sequence of links which contains items. Each link contains a
connection to another link.
Syntax: Linkedlist object = new Linkedlist();
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List
Singly Linked List: In a singly Linked list each node in this list stores the data of the node and
a pointer or reference to the next node in the list. Refer to the below image to get a better
understanding of single Linked list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and
another to previous node. You can refer to the below image to get a better understanding of
doubly linked list.
LinkedList example:
import java.util.*;
public class LinkedlistExample
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();// creating linked list
al.add("Rachit"); // adding elements
al.add("Rahul");
al.add("Rajat");
Iterator<String> itr = al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above program would be:
Rachit
Rahul
Rajat
Vectors: Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector. Vector implements a dynamic array. Also, the vector is
not limited to a specific size, it can shrink or grow automatically whenever required. It is
similar to ArrayList, but with two differences :
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Syntax:
Vector object = new Vector(size, increment);
Below are some of the methods of the Vector class:
Method Description
add(E e) For appending the given element e in the given vector.
add(int index, E e) For inserting the given element, e, at the given index.
For appending all the elements from collection c to the java
addAll(Collection c)
vector.
addAll(int index, Collection For inserting all the elements present in the given collection c to
c) the given java vector at the given index.
capacity() For getting the length of the actual array inside the vector.
clear() For removing all of the elements from the given vector in java.
firstElement() For getting the first object of the vector present at index 0.
For getting the element at the given index from the Vector in
get(int index)
java.
Method Description
For finding out the index of the first occurrence of the specified
indexOf(Object o) element in this java vector. Keep in mind, if the element is not
present, it will return -1.
insertElementAt(E element,
For inserting the given element at the index in this java vector.
int index)
isEmpty() For finding if the vector in java has any elements in it or not.
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.
The stack data structure has the two most important operations that are push and pop. The
push operation inserts an element into the stack and pop operation removes an element
from the top of the stack. Let's see how they work on stack.
E push(E item) The method pushes (insert) an element onto the top of the
stack.
E pop() The method removes an element from the top of the stack
and returns the same element as the value of that function.
E peek() The method looks at the top element of the stack without
removing it.
int search(Object The method searches the specified object and returns the
o) position of the object.
import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Sets
A set is an unordered collection of objects in which duplicate values cannot be stored. This
collection is used when we wish to avoid the duplication of the objects and wish to store
only the unique objects. This set interface is implemented by various classes
like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we
can instantiate a set object with any of these classes. For example,
Set<T> hs = new HashSet<> ();
Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = 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.
Below are some of the methods of Java HashSet class:
Method Description
boolean add(Object o) Adds the specified element to this set if it is not already present.
boolean contains(Object o) Returns true if the set contains the specified element.
Returns a shallow copy of the HashSet instance: the elements themselves are
Object clone()
not cloned.
Hashset Example:
import java.util.*;
class HashsetExample
{
public static void main(String args[])
{
HashSet <String> al=new HashSet <String>(); // creating hashSet
al.add("Rachit"); // adding elements
al.add("Amit");
al.add("jack");
Iterator <String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above code would be:
Amit
Rachit
jack
Linked Hashset :
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.
A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked
list to store the data and retains the ordering of the elements.
TreeSet : TreeSet class implements the Set interface that uses a tree for storage. The objects
of this class are stored in the ascending order. Also, it inherits AbstractSet class and
implements NavigableSet interface. It contains only unique elements like HashSet. In
TreeSet class, access and retrieval time are faster.
Below are some of the methods of Java TreeSet class:
Method Description
boolean addAll(Collection c) Add all the elements in the specified collection to this set.
boolean contains(Object o) Returns true if the set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
void add(Object o) Add the specified element to the set.
void clear() Removes all the elements from the set.
Object clone() Return a shallow copy of this TreeSet instance.
Object first() Return the first element currently in the sorted set.
Object last() Return the last element currently in the sorted set.
int size() Return the number of elements in the set.
TreeSet example:
import java.util.*;
class TreeSetExample{
public static void main(String args[]){
TreeSet <String> al=new TreeSet <String>(); // creating treeSet
al.add("John"); // adding elements
al.add("Sam");
al.add("Rick");
Iterator <String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above program would be:
John
Rick
Sam
Now you must be wondering what is the difference between all these sets?
HashSet stores elements in random order whereas LinkedHashSet stores elements according
to insertion order and TreeHashSet stores according to natural ordering.
Java collections: Queue
Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out manner.
In a queue, the first element is removed first and last element is removed in the end. Each
basic method exists in two forms: one throws an exception if the operation fails, the other
returns a special value.
Also, priority queue implements Queue interface. The elements of the priority queue are
ordered according to their natural ordering, or by a Comparator provided at the queue
construction time. The head of this queue is the least element with respect to the specified
ordering.
Below are some of the methods of Java Queue interface:
Method Description
boolean add(object) Inserts the specified element into the queue and returns true if it is a success.
boolean offer(object) Inserts the specified element into this queue.
Object remove() Retrieves and removes the head of the queue.
Retrieves and removes the head of the queue, or returns null if the queue is
Object poll()
empty.
Object element() Retrieves, but does not remove the head of the queue.
Retrieves, but does not remove the head of this queue, or returns null if the
Object peek()
queue is empty.
class GfG
{
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
Output:
10
10
15