Collections in Java | Java Collection Framework

Collection in java

The collections in java provide an architecture to store and manipulate the group of objects, interfaces and classes. A collection is a group of objects or it is a single entity that represents multiple objects.

Java collection framework consists of classes and interfaces by using these classes and interface developers can represent a group of objects in a single entity. Collection framework is present in package java. util

What is collections in Java?

The Collections in Java provides an architecture to store and manipulate the group of objects, interfaces and classes. This java collection is a framework. This framework has several useful functions that have tons of useful functions, making a programmer task super easy.

This framework provides many interfaces (Queue, Set, List, Deque) and classes ( PriorityQueue, HashSet, ArrayList, Vector, LinkedList, LinkedHashSet).

Framework in java

Java frameworks are the prewritten code used by developers to create applications in the java language. 

What is the Collection framework?

The Collection framework is a unified architecture for storing and manipulating a group of objects.

The collection framework was designed to meet several goals, such as −

  • The framework had to be high-performance and adapt a collection easy method.
  • The implementations for the fundamental collections were to be highly efficient.
  • The framework had to allow different types of collections to work in a similar manner.
  • The framework had to extend and/or adapt a collection easily.

Collection Framework Hierarchy

Let us see the hierarchy of the collection framework:

Hierarchy of Collection Framework

What is a need for the Collection Framework?

Suppose, A variable is created to store data and a 10 value is assigned (Example, int a =10). Now the programmer wants to store another data of the same datatype. So, the programmer needs to create another variable and assign a new value (Example, int b= 20). 

If the programmer wants to store 100 values then the disadvantage of this is the programmer has to create multiple variables with a unique name and it is very time-consuming also.

In this case array concept is introduced. Programmer declare an array with specific size and store elements.

For example,

int  arr[] = new int[100]; // 100 is size of array 
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
.
.
.
arr[100] = 90;

This is the way of store multiple values of the same datatype.

But there are certain limitations 

  1. Array
    Array stores the values of the same datatype i.e., Array is homogeneous but it can overcome by creating an array of object classes but this is not a good option.
Public class MultipleValues
{
Public static void main( string[] args)
{
objects a[]- new objects [5];
a[0]=10;
a[1]=10.45;
a[2]='A';
a[3]="name";
a[4]= true;
For( int i=0;i<a.leanght;i++)
{
system.out.println(a[1]);
}
}
}


The main limitation is an array has a fixed size (not growable) i.e., 

In the above example array is created with a size of five which means the array store only five data values. 

If the size of the array is five and the user store only four values then memory is wasted.

To overcome this limitation, the Collection Framework was used.

In the collection framework, there are classes and interfaces are defined which are List, Queue, Set, etc. 

Sr.noArrayCollection Framework
1Fixed-size (not growable)Growable in nature
2If the size is 10 and only 5 elements store then it is a waste of memory.It adjusts size according to elements.
3Arrays can hold only homogeneous data elements.Collection can hold homogeneous as well as heterogeneous data elements.
4Memory management is poor.Memory management is effective.

Also Read: Strings in Java

Difference between collection and collections

The collection in java is the root interface of the collection framework and provide several classes and interfaces to represent a group of individual objects as a single unit.

List, Set, and Queue are the main child interfaces of the collection interface.

The Map interface is also part of the java collection framework but it does not inherit the collection interface. The map interface is preferred when values are stored in the form of keys and value pairs.

Map Interface implemented using following classes:-

  • Hashmap
  • LinkedHashmap
  • HashTable

Methods present in the collection interface

Sr.noMethodDescription
1add(Object o)To insert an element in the collection.
2addAll(Collection c)To insert another collection in the present collection.
3remove(Object o)To remove an element in the collection.
4removeAll(Collection c)To remove another collection from the present collection if another is inserted.
5retain(collection c)To remove all the collection elements that are not contained in the specified collection.
6clear()It removes all the elements from the collection.
7isEmpty()It checks collection is empty or not and provides true or false.
8size()It gives the total number of elements present in the collection in form of a numeric value.
9equals(collection c)It is used to check if the two collections are the same or not.
10toArray(collection c)It converts collection into an array.
11contains(Object o)It is used for searching. If an element is present in the collection it returns true or false.
12contains(collection c)It is used for searching. If elements of another collection are present in the collection or not. If present returns true or false.

List Interface

  • The list is a child interface of Collections in java.
  • Insertion order preserved i.e., They appear in the same order in which we inserted.
  • Duplicate elements are allowed.

    List Interface is implemented by using ArrayList, LinkedList, and Vector class.

ArrayList

  • ArrayList is a class present in java. util package.
  • It provides a dynamic array for storing the element.
  • It is an array but there is no size limit.
  • We can add or remove elements easily.
  • It is more flexible than a traditional array.

How to create ArrayList

ArrayList<DataType> VariableName=new ArrayList<DataTYpe>()

For example,

1. This is way is to store values of the same datatype

import java.util.*;
public class ListArryList
{
Public static void main(String[] args
{
ArryList < String>name =new ArrayList<String>();
name.add("Pinku');
name.add("seeta");
name.add("geeta");
name.add("sara");
name.add("ved');
System.out.println(name);
}
}

2. This is way is to store values of different datatype

import java.util.*;
public class ListArraylist
{
public static void main(String[]args)
{
ArrayList name= new ArrayList();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}

Methods in ArrayList:

Sr.noMethodDescription
1get(object o)It prints the value at a specific index.
2set(index, object o)It updates the value. In that, we need to provide an index.
3add(index, object o)It adds an element at a specific index.
4remove(Object o)It removes elements at specific indexes.
5sort()It sorts an array depending upon the data type.
6addAll(Collection c)It is used to add another collection.
7removeAll(Collection c)It is used to remove another collection.

The common methods in the elements are shown below.

toArray() method

import java.util.*;
public class Main
{
public static void main(String[] args) {
ArrayList<Integer> values=new ArrayList<Integer>();
values.add(10);
values.add(20);
values.add(30);
values.add(40);
values.add(50);
Object arr[] = values.toArray();
System.out.println("After convert into an array");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}

Ways to reading elements from any list

  • For loop
  • For …. Each loop
  • Iterator
import java.util.*;
public class Main
{
public static void main(String[] args)
{
ArrayList<String> animal=new ArrayList<String>();
animal.add("Dog");
animal.add("Tiger");
animal.add("Lion");
animal.add("Fox");
animal.add("Rabbit");
System.out.println("By using get() method");
System.out.println(animal.get(3)); // Fox
System.out.println("By using set() method");
animal.set(1,"Bear"); // Updating values
System.out.println("After Updating values");
System.out.println(animal);
System.out.println("by using add(index,Object) method");
System.out.println("After adding specific element in given index position");
animal.add(2, "Mouse");
System.out.println(animal);
System.out.println("by using remove(Object) method");
System.out.println("After reomoving specific element");
animal.remove("Mouse");
System.out.println(animal);
System.out.println("By using sort() method");
Collections.sort(animal); //Sorting an array
System.out.println("After sorting");
import java.util.*;
public class Main
{
public static void main(String[] args)
{
ArrayList values=new ArrayList();
values.add(10);
values.add(106.444);
values.add("suresh");
values.add('D');
values.add(true);
System.out.println("Ways to Read the data:- 1.for loop, 2.for each loop,
3.iterator");
System.out.println("1.For loop");
for(int i=0;i<values.size(); i++)
{
System.out.println(values.get(i));
}
System.out.println("2.for Each loop");
for(Object i : values)
{
System.out.println(i);
}
System.out.println("3.iterator");
Iterator itr = values.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
public class Main
{
public static void main(String[] args)
{
ArrayList<Integer> values=new ArrayList<Integer>();
values.add(10);
values.add(20);
values.add(30);
values.add(40);
values.add(50);
System.out.println("first collection");
System.out.println(values);
ArrayList<Integer> values 2 = new ArrayList<Integer>();
values2.add(60);
values2.add(70);
values2.add(80);
values2.add(90);
values 2.add(100);
values 2.add(110);
System.out.println("second collection");
System.out.println(values2);
System.out.println("After adding second collection");
values.addAll(values2);
System.out.println(values);
System.out.println("After removing second collection");
values.removeAll(values2);
System.out.println(values);

LinkedList

  • LinkedList class uses a doubly LinkedList to store element. i.e., the user can add data at the first position as well as the last position.
  • The dequeue interface is implemented using the LinkedList class.
  • Null insertion is possible.
  • If we need to perform insertion /Deletion operation the LinkedList is preferred.
  • LinkedList is used to implement Stacks and Queues.

    How LinkedList works?

Consider LinkedList contains 3 elements,

LinkedList element is not stored at the consecutive address they stored at any address but they internally connected using the address of previous and next element address.

PA :-Previous Element address  NA:- Next Element Address      index:0,1,2,….

How to create a LinkedList

LinkedList<DataType> VariableName = new LinkedLits < DataType>();

For example,

  1. This is way is to store values of the same datatype
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedList <Integer> name = new LinkedList<Integer>();
name.add(100);
name.add(200);
name.add(300);
name.add(400);
name.add(5000);
System.out.println(name);
}
}
  1. This is way is to store values of different datatype
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedList name = new LinkedList();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}

Methods in LinkedList:

Some methods in LinkedList are the same as ArrayList. Refer program no. 4, 5, 6, 7. change is to replace ArrayList with LinkedList.

Other methods in LinkedList are:

  • addFirst()
  • addLast()
  • removeFirst()
  • removeLast()
  • getFirst()
  • getLast()
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("C");
list.add("C++");
list.add("Python");
list.add("Java");
list.add("PHP");
System.out.println("Original list is: "+ list);
list.addFirst("scala");
list.addFirst("HTML");
System.out.println("After adding element by using addFirst() method: " + list);
list.removeFirst();
System.out.println("After adding element by using removeFirst() method: " + list);
System.out.println("After adding element by using getFirst() method: " + list.getFirst());
list.addLast("CSS");
System.out.println("After adding element by using addLast() method: " + list);
list.removeLast();
System.out.println("After adding element by using removeLast() method: " + list);
System.out.println("After adding element by using getLast() method: " + list.getLast());
}
}

Vector

  • Every method is synchronized.
  • The vector object is Thread safe.
  • At a time only one thread can operate on the Vector object.
  • performance is low because Threads are needed to wait.

How to create a list using vector

Vector < DataType> VariableName = new Vector<DataType> ();

 

import java.util.*;
public class Main
{
public static void main(String[] args) {
Vector<String> lis = new Vector<String>();
System.out.println("In vector addElement() method is also used to
add elements ");
lis.add("Tiger");
lis.add("Lion");
lis.add("Dog");
lis.add("Elephant");
lis.addElement("Rat");
lis.addElement("Cat");
lis.addElement("Deer");
System.out.println(lis);
}
}

Methods in vector:

Some methods in Vector is same as Arraylist. Refer program no.4, 5, 6, 7  . change is replace ArrayList to Vector.

Another methods are:

addElement()

firstElement()

lastElement()

import java.util.*;
public class Main
{
public static void main(String[] args) {
Vector<String> lis = new Vector<String>();
System.out.println("In vector addElement() method is also used to add elements ");
lis.add("Tiger");
lis.add("Lion");
lis.add("Dog");
lis.add("Elephant");
lis.addElement("Rat");
lis.addElement("Cat");
lis.addElement("Deer");
System.out.println(lis);
System.out.println("The first animal is = "+lis.firstElement());
System.out.println("The last animal is = "+lis.lastElement());
}
}

Stack

  • It is the child class of Vector.
  • It is based on LIFO (Last In First Out) i.e., Element inserted in last will come first.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Stack<Integer s = new Stack<>();
s.push(11);
s.push(33);
s.push(145);
s.push(18);
s.push(91);
System.out.println(s);
int n = s.peek();
System.out.println("Peek is used to get element: "+n);
s.pop();
System.out.println("After using pop method: "+s);
}
}

Set Interface

  •   Set is a child interface of Collection.
  • Insertion order not preserved i.e., They appear in the different order in which we inserted. 
  • Duplicate elements are not allowed.
  • Heterogeneous objects are allowed.

     Set Interface is implemented by using LinkedHashSet and HashSet class.

Hashset

  • HashSet stores the elements by using Hashing mechanism.
  • It contains unique elements only.
  • This hashSet allows null values.
  • It does not maintain insertion order. It inserted elements based on their hashcode.
  • HashSet is the best approach for the search operation.

There are three different ways to create HashSet:

  1. HashSet hs = new Hashset();

Here, HashSet default capacity to store elements is 16 with a default load factor/fill ratio of 0.75.

Load factor is if HashSet stores 75% element then it creates a new HashSet with increased capacity.

2. Hashset hs = new Hashset ( 100);

     Here 100 is an initial capacity and the default load factor is 0.75.

3. Hashset hs = new Hashset ( 100,(foot) 0.90);

Here capacity is 100 with a load factor of 0.90. The load factor may be decided by the user but it should be >=0.75.

4. HashSet<Integer> hs = new Hashset < Integer> ();

import java.util.*;
public class Main
{
public static void main(String[] args) {
HashSet name = new HashSett();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}

Method in HashSet

Some methods are common in HashSet and Arraylist refer to program no. 4, 5, 6, 7. 

In HashSet get() and set() method not present because forget and set method index is required and in HashSet elements stores at a random address

Problem Statement:-

Write a program to remove duplicate elements.

import java.util.*;
public class Main
{
public static void main(String[] args)
{
int a[]={1,1,1,2,3,5,5,5,6,6,9,9,9,9};
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<a.length;i++)
{
hs.add(a[i]);
}
for(int i:hs)
{
System.out.print(i+" ");
}
}

LinkedHashSet

  • The LinkedHashSet class extends the HashSet class.
  • The basic data structure is a combination of LinkedList and Hashtable.
  • Insertion order is preserved.
  • Duplicates are not allowed.
  • LinkedHashSet is non synchronized.
  • LinkedHashSet is the same as HashSet except the above two differences are present.

for example

import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedHashSet name = new Linked HashSett();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}
  1. SortedSet
  • SortedSet implements (child interface) Set Interface.
  • If we want to insert unique elements where duplicates are not allowed and all elements should be inserted according to some sorting order then we should go for the SortedSet interface.
  • Sorting order can be either default sorting  (or) user can decide sorting order.

TreeSet

  • Java TreeSet class implements the Set interface that uses a tree structure to store elements.
  • It contains Unique Elements.
  • TreeSet class access and retrieval time are very fast.
  • It does not allow null elements.
  • It maintains Ascending Order.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
TreeSet <String> animal=new TreeSet<String>();
animal.add("Dog");
animal.add("Tiger");
animal.add("Lion");
animal.add("Fox");
animal.add("Rabbit");
System.out.println(animal);
System.out.println(animal.descendingSet());
System.out.println(animal.pollFirst());
System.out.println(animal.polllast());
System.out.println(animal.headset("Lion"));
System.out.println(animal.tailSet("Fox"));
}
}

Queue Interface

  • The queue implements FIFO i.e., First In First Out which means the elements entered first comes out first.
  • Queue interface is provided in java. util package and implements the collection interface.
  • The queue is implemented by LinkedList, priority queue classes, and ArrayDequeue Interface. PriorityQueue is allowed homogeneous data while LinkedList allows heterogeneous as well as homogeneous data.
  • Dequeue is a linear collection that supports element insertion and removal at both sides. Null elements are not allowed in the dequeue.

ArrayDequeue is faster than LinkedList. 

Methods in Queue :

add() :- It used to insert data into queue. If data is not inserted successfully it throws an exception.

offer():- It is used to insert data into the queue. If data is not inserted successfully it returns false.

element():-It returns head elements from the queue. If Queue is empty it will throw exception NoSuchElementException.

peek():- It returns head elements from the queue. . If Queue is empty it will return Null.

remove():- It removes an element from the queue. If Queue is empty it will throw exception NoSuchElementException.

poll():- It removes the element from the removing. If Queue is empty it will return Null.

import java.util.*;
public class Main
{
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
q.add("A");
q.add("B");
q.add("C");
q.add("D");
q.add("E");
q.add("F");
System.out.println(9);
System.out.println(q.element());//if queue is empty : NOSuchElementExceptiom
System.out.println(q.peek());//if queue is empty : null
System.out.println("After remove head element: "+q);
System.out.println("It removes head element whic is: "+q.remove());
System.out.println("After remove head element by using poll() method: "+q);
System.out.println("It removes head element whic is: "+q.poll());
Iterator itr = q.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Map Interface

  • A map is a part of the collection framework but it does not implement a collection interface.
  • A map stores values based on Key and value Pair.
  • Duplicate value of the key is not allowed. In short,

Key must be unique while duplicates values are allowed.

  • Map Interface
  •  HashMap
  • LinkedHashMap
  • Hashtable

HashMap

  • Map Interface is implemented by HashMap.
  • HashMap stores the elements by using a mechanism called Hashing.
  • It contains values based on the key-value pair.
  • It contains a unique key.
  • It can store one Null key and Multiple null values.
  • Insertion order is not maintained and it is based on the hash code of the keys.
  • HashMap is Non-Synchronized.
  • How to create HashMap

HashMap < dataType, dataType> m = new HashMap < dataType,dataType>();

For example,

import java.util.*;
public class Main
{
public static void main(String[] args) {
HashMap <Integer,String> m = new HashMap <Integer,String>();
m.put(1,"seeta");
m.put(2,"geeta");
m.put(3,"reeta");
m.put(4,"neeta");
m.put(5,"piku");
System.out.println(m);
}
}

import java.util.*;
public class Main
public static void main(String[] args) {
HashMap <Integer, String> m = new HashMap <Integer, String>();
m.put(1,"seeta");
m.put(2,"geeta");
m.put(3,"reeta");
m.put(4,"neeta");
m.put(5,"piku");
System.out.println(m);
System.out.println(m.get(5));
m.remove(3);
System.out.println(m);
System.out.println(m.containsKey(2));
System.out.println(m.containsValue("neeta"));
System.out.println(m.containsKey(6));
System.out.println(m.containsValue("jeena"));
System.out.println(m.isEmpty());
System.out.println(m.keySet());
System.out.println(m.values());
System.out.println(m.entrySet());
System.out.println("Method to print key and values together");
for(Object i:m.keySet())

LinkedHashMap

  • The basic data structure is a combination of LinkedList and Hashtable.
  • It is the same as HashMap except above difference.

Hashtable

  • A Hashtable is an array of lists. Each list is known as a bucket. 
  • A hashtable contains values based on key-value pair.
  • It contains unique elements only.
  • Hashtable class does not allow null key as well as value otherwise it will throw NullPointerException.
  • Every method is synchronized. i.e At a time only one thread is allowed and the other threads are on a wait.  
  • Performance is poor as compared to HashMap.  

How to create HashMap

There are three ways:

Hashtable t = new Hashtable();

  1. Here default capacity is 11, the load factor is 0.75. (Load factor refer HashSet)
    Hashtable t = new hashtable ( initial Capacity );
  2. Here Hashtable is created with some capacity
    Hashtable t = new hashtable ( initial capacity, fillration/load factor);

Here Hashtable is created with some capacity and the load factor is decided by the user. It should be >=0.75.

Note:- Methods in Hashtable are the same as Hash Map.

Advantages of collections framework

  • Not necessary to learn multiple ad hoc collection APIs.
  • It provides a standard interface for collections and also provides algorithms to manipulate them.
  • It reduces the programming efforts by providing useful data structures and algorithms.
  • Can establish a common language to pass collections back and forth that provides compatibility between unrelated APIs.
  • The collection is resizable and can grow.

Difference between Iterator and ListIterator

FeaturesListIteratorIterator
Traversal DirectionBoth, forward and backwardForward
ModifyCan modify or replace elementsCannot modify or replace elements
Objects traversalList onlyMap, Set and List
Add and Set operationsAllows both operationsNot possible
Iterator’s current positionCan be determinedNot possible.
Retrieve IndexYesNot possible

Difference between Comparable and Comparator

ComparableComparator
Comparable provides a single sorting sequence.The Comparator provides multiple sorting sequences.
Comparable affects the original class.Comparator doesn’t affect the original class.
Comparable provides compareTo() method to sort elements.Comparator provides compare() method to sort elements.
Comparable is present in java.lang package.A Comparator is present in java. util package.
Comparable interface compares “this” reference with the object specified.Comparator in Java compares two different class objects provided.

We hope this blog on collection in Java was helpful!

Embark on a learning adventure like no other with our extensive collection of free online courses. Whether you’re interested in diving into the world of Cybersecurity, mastering the art of Management, exploring the wonders of Cloud Computing, or delving into the intricate realm of IT and Software, we have courses that cater to your interests and goals.

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top