Unit-3 Collections Part 1
Unit-3 Collections Part 1
UNIT – III
Collections : Any group of individual objects that are represented as a single
unit is known as a Java Collection of Objects.
Framework
A framework provides a ready-made structure of classes and interfaces for
building software applications efficiently. It simplifies adding new features by
offering reusable components that perform similar tasks, eliminating the need
to create a framework from scratch for each new project. This approach
enhances object-oriented design, making development quicker, more
consistent, and reliable.
The Java Collections Framework (JCF) provides a set of classes and interfaces
to handle different types of collections such as lists, sets, queues, and maps.
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
1. Vector
Description: A resizable array that grows dynamically.
Key Features:
o Synchronized, making it thread-safe.
o Can hold any type of objects, but is less efficient than ArrayList.
Methods: addElement(), removeElement(), size(), capacity().
Replacement: ArrayList (unsynchronized version)
or CopyOnWriteArrayList (synchronized version).
2. Stack
Description: A subclass of Vector implementing the LIFO (Last In, First
Out) stack data structure.
Key Features:
o Thread-safe but inefficient compared to modern alternatives.
Methods: push(), pop(), peek(), empty().
Replacement: Deque (like ArrayDeque) from the Collections Framework.
3. Hashtable
Description: A dictionary-like collection to store key-value pairs.
Key Features:
o Synchronized, thread-safe, but less efficient compared to modern
classes.
o Does not allow null keys or values.
Methods: put(), get(), remove(), containsKey().
Replacement:
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
4. Enumeration
Description: An interface used to iterate over elements in
legacy collections like Vector and Hashtable.
Key Features:
o Limited functionality compared to modern iterators.
Methods: hasMoreElements(), nextElement().
Replacement: Iterator and Iterable interface in the Collections
Framework.
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Interfaces like :
List
Set
Queue
Deque
Maps
Classes like :
ArrayList
Vector
LinkedList
PriorityQueue
HashSet
LinkedHashSet
TreeSet
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
ArrayList
LinkedList
Vector
Stack
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.
Example Program :
import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
//Creating arraylist
list.add("Grapes");//Adding object in
arraylist list.add("Kiwi");
list.add("Banana");
list.add("Apple");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext())
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
{
System.out.println(itr.next());
}
}
}
Output:
Grapes
Kiwi
Banana
Apple
import java.util.*;
public class TestJavaCollection2
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<>();
al.add("Mango");
al.add("Cherry");
al.add("Apple");
al.add("Grapes");
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :
Mango
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Cherry
Apple
Grapes
Example Program :
import java.util.*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Example Program :
import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> s = new Stack<String>();
s.push("Ayush");
s.push("Garvit");
s.push("Amit");
s.push("Ashish");
s.push("Garima");
s.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
2. Set : A collection that does not allow duplicates and does not guarantee
any specific order.
import java.util.*;
public class TestJavaCollection7
{
public static void main(String args[])
{
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
import java.util.*;
public class TestJavaCollection8
{
public static void main(String args[])
{
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
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.
import java.util.*;
public class TestJavaCollection9
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
The Queue interface is part of the java.util package and provides methods for
adding, removing, and inspecting elements in a queue. The main operations
of a queue are:
1. add(E e): Adds the specified element to the queue. If the queue
cannot accommodate the element, an exception is thrown.
2. offer(E e): Similar to add, but returns false if the queue cannot
accommodate the element (rather than throwing an
exception).
3. remove(): Removes and returns the head of the queue. Throws
an exception if the queue is empty.
4. poll(): Removes and returns the head of the queue, or returns null if
the queue is empty.
5. peek(): Returns the head of the queue without removing it. Returns
null if the queue is empty.
6. element(): Similar to peek, but throws an exception if the queue
is empty.
a) LinkedList
b) PriorityQueue
a) LinkedList
Example Program :
import java.util.LinkedList;
import java.util.Queue;
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
b) PriorityQueue
A priority queue is a type of queue where each element is
associated with a priority.
The elements are ordered based on their natural ordering or by
a custom comparator.
Unlike LinkedList, it does not maintain the FIFO order but orders the
elements based on their priority.
Example Program :
import java.util.PriorityQueue;
import java.util.Queue;
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
{
Queue<Integer> queue = new PriorityQueue<>();
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
5.Maps:
In Java, the Map interface represents a collection of key-value pairs, where each
key is associated with exactly one value. A Map does not extend the
Collection interface, as it stores key-value pairs instead of just elements.
The Map interface is part of the java.util package, and it defines methods to
manipulate key-value pairs such as adding, removing, and retrieving values.
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
put(K key, V value): Associates the specified value with the specified key
in the map. If the map already contains the key, the old value is replaced
by the new value.
get(Object key): Returns the value to which the specified key is
mapped, or null if the map contains no mapping for the key.
containsKey(Object key): Returns true if the map contains a mapping
for the specified key.
containsValue(Object value): Returns true if the map maps one or more
keys to the specified value.
remove(Object key): Removes the mapping for the specified key
from the map, if present.
keySet(): Returns a Set view of the keys contained in the map.
values(): Returns a Collection view of the values contained in the map.
entrySet(): Returns a Set view of the mappings contained in the
map, where each element is a Map.Entry.
size(): Returns the number of key-value mappings in the map.
isEmpty(): Returns true if the map contains no key-value mappings.
1. HashMap
o Implements the Map interface and stores key-value pairs using
a hash table.
o It allows null for both keys and values.
o No predictable order: It does not guarantee any specific order
of elements (not sorted).
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
2. TreeMap
o Implements the Map interface and stores key-value pairs in
a sorted order.
o It orders the keys according to their natural ordering or by
a specified comparator.
o Does not allow null keys but allows null values.
3. LinkedHashMap
o Extends HashMap and maintains a linked list of entries in
the order they were added.
o Retains the insertion order (or access order if specified),
unlike HashMap.
4. Hashtable
o An older implementation of Map (now mostly replaced
by HashMap).
o Synchronized and does not allow null keys or values.
5. ConcurrentHashMap
o A thread-safe version of HashMap for concurrent use.
o Allows multiple threads to read and write to the map
simultaneously, with better performance compared to
Hashtable.
Example Program :
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Points to remember:
………………………………………………………………………………………………………………………
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
1. hasNext():
o Checks if there are more elements in the collection to iterate over.
o Returns true if there is at least one more element,
otherwise returns false.
2. next():
o Returns the next element in the collection.
o Throws NoSuchElementException if no more elements
are available.
3. remove() (optional):
o Removes the last element returned by the iterator from
the collection.
o This method is optional and might throw
UnsupportedOperationException if not supported by
the collection.
Example Program
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Output :
10
20
30
40
Comparator Interface :
A comparator interface is used to order the objects of user-defined classes. A
comparator object is capable of comparing two objects of the same class.
Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2);
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Method 1: One obvious approach is to write our own sort() function using one
of the standard algorithms. This solution requires rewriting the whole sorting
code for different criteria like Roll No. and Name.
Method of Collections class for sorting List elements is used to sort the
elements of List by the given comparator.
Methods in Comparator
2. equals(Object obj)
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
// Constructor
public Student(int rollno, String name, String address)
{
// This keyword refers to current instance itself
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
}
}
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}
// Class 4
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty ArrayList of Student type
ArrayList<Student> a = new ArrayList<Student>();
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc
Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
ArrayList
Vector
CopyOnWriteArrayList (from java.util.concurrent)
Example Program
import java.util.*;
public class RandomAccessDemo {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
List<String> l2 = new LinkedList<>();
l2.add("Charlie");
l2.add("Dave");
Prepared By,
Ayesha S, Assistant Professor, MJCET
MUFFAKHAM JAH COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ARTIFICIAL INTELLIGENCE
1. Consistent API: The API has a basic set of interfaces like Collection, Set,
List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that
implement these interfaces have some common set of methods.
Prepared By,
Ayesha S, Assistant Professor, MJCET