0% found this document useful (0 votes)
4 views33 pages

Java Unit 4 CodeWithSubhsam

The Java Collection Framework provides a structured way to store, manage, and manipulate groups of data through various interfaces and classes, including List, Set, Queue, and Map. Key features include built-in methods for adding, removing, and iterating over elements, as well as algorithms for sorting and searching. The framework supports different types of collections, each with unique properties and implementations, such as ArrayList, HashSet, and PriorityQueue.

Uploaded by

12pcm.deepak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

Java Unit 4 CodeWithSubhsam

The Java Collection Framework provides a structured way to store, manage, and manipulate groups of data through various interfaces and classes, including List, Set, Queue, and Map. Key features include built-in methods for adding, removing, and iterating over elements, as well as algorithms for sorting and searching. The framework supports different types of collections, each with unique properties and implementations, such as ArrayList, HashSet, and PriorityQueue.

Uploaded by

12pcm.deepak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

✅ Collection Framework in Java

The Java Collection Framework is a set of classes and interfaces that help you
store, manage, and manipulate a group of data (objects) in a structured way.

🔷 Main Components
1. Interfaces (Blueprints)

These define the standard operations for each type of collection:

Interface Use

Collectio Root of all collection classes


n

List Ordered, allows duplicates (e.g. ArrayList)

Set No duplicates (e.g. HashSet)

Queue FIFO structure (e.g. PriorityQueue)

Map Key-value pairs (e.g. HashMap) (Not part of Collection


interface)

2. Classes (Implementation)

CodeWithSubhsam
■ Click here to access the resource
Interfac Common Classes
e

List ArrayList, LinkedList

Set HashSet, LinkedHashSet, TreeSet

Queue PriorityQueue, ArrayDeque

Map HashMap, TreeMap,


LinkedHashMap

🧠 Why Use Collection Framework?


📦 Group data storage (no need for arrays only)
🔄 Built-in methods: add, remove, sort, search
●​

⚙️ Algorithms: sorting, shuffling (via Collections class)


●​
●​

🔹 1. Collection in Java (Interface)


●​ Collection is an interface in Java.
●​ It is the root interface of all collection types like List, Set, Queue.
●​ It provides common methods like:
○​ add(), remove(), size(), clear()

🔹 2. Collection Framework in Java


●​ Collection Framework is the entire architecture or system.
●​ It includes:
○​ Interfaces (Collection, List, Set, Map, etc.)
○​ Classes (ArrayList, HashSet, TreeMap, etc.)
○​ Algorithms (Collections.sort(), shuffle(), etc.)

CodeWithSubhsam
■ Click here to access the resource
🔰 Java Collection Framework Hierarchy

🔁 Iterator Interface in Java


✅ What is Iterator?
Iterator is an interface used to traverse (loop through) elements of a Collection (like
ArrayList, HashSet, etc.).

It helps in accessing one element at a time, and also allows removing elements while
iterating.

CodeWithSubhsam
■ Click here to access the resource
📦 Defined in:
java.util.Iterator

🔑 Important Methods of Iterator:


Method Description

hasNext Returns true if there are more elements


()

next() Returns the next element

remove( Removes the last element returned by


) next()

✅ Code Example:
import java.util.*;

public class Main {

​ public static void main(String[] args) {

​ List<String> names = new ArrayList<>();

​ names.add("Saurabh");

​ names.add("Ravi");

​ names.add("Amit");

CodeWithSubhsam
■ Click here to access the resource
​ Iterator<String> itr = names.iterator();

​ while (itr.hasNext()) {

​ String name = itr.next();

​ System.out.println(name);

​ }

​ }

🧾 Output:
Saurabh

Ravi

Amit

✅ Collection Interface in Java


📌 Definition:
Collection is the root interface of the Java Collection Framework.​
It represents a group of elements (objects) and defines common operations that all
collections (like List, Set, Queue) must support.

CodeWithSubhsam
■ Click here to access the resource
🔷 Located in:
java.util.Collection

🔑 Key Methods in Collection Interface:


Method Description

add(E e) Adds an element

remove(Object Removes a specific element


o)

size() Returns number of elements

isEmpty() Checks if collection is empty

contains(Object Checks if element is present


o)

clear() Removes all elements

iterator() Returns an Iterator for


traversal

📚 Subinterfaces of Collection:
Collection<E>

|-- List<E> ​(e.g. ArrayList, LinkedList)

CodeWithSubhsam
■ Click here to access the resource
|

|-- Set<E> ​ (e.g. HashSet, TreeSet)

|-- Queue<E> ​ (e.g. PriorityQueue, LinkedList)

✅ List Interface in Java


📘 Definition:
The List interface is a child of the Collection interface.​
It represents an ordered collection — you can access elements by index, and it
allows duplicate elements.

📦 Defined in:
java.util.List

🧠 Common Classes that Implement List:


Class Description

ArrayList Fast for accessing elements


(indexing)

LinkedList Good for insert/delete in between

CodeWithSubhsam
■ Click here to access the resource
Vector Thread-safe (not commonly used
now)

Stack LIFO stack built on Vector

🔰 Common List Implementations:


Type Ordered Allows Thread-safe Allows
? Duplicates? ? nulls?

ArrayList ✅ Yes ✅ Yes ❌ No ✅ Yes


LinkedList ✅ Yes ✅ Yes ❌ No ✅ Yes
Vector ✅ Yes ✅ Yes ✅ Yes ✅ Yes
Stack (extends ✅ Yes ✅ Yes ✅ Yes ✅ Yes
Vector)

✅ Common Methods of the List Interface (Available in all its


implementations):
Method ArrayLis LinkedLis Vector Stack
t t

add(E e) ✅ Yes ✅ Yes ✅ ✅


Yes Yes

add(int index, E ✅ Yes ✅ Yes ✅ ✅


element) Yes Yes

remove(Object o) ✅ Yes ✅ Yes ✅ ✅


Yes Yes

remove(int index) ✅ Yes ✅ Yes ✅ ✅


Yes Yes

CodeWithSubhsam
■ Click here to access the resource
get(int index) ✅ Yes ✅ Yes ✅ ✅
Yes Yes

set(int index, E ✅ Yes ✅ Yes ✅ ✅


element) Yes Yes

contains(Object o) ✅ Yes ✅ Yes ✅ ✅


Yes Yes

size() ✅ Yes ✅ Yes ✅ ✅


Yes Yes

isEmpty() ✅ Yes ✅ Yes ✅ ✅


Yes Yes

clear() ✅ Yes ✅ Yes ✅ ✅


Yes Yes

iterator() ✅ Yes ✅ Yes ✅ ✅


Yes Yes

✅ Common Methods with Examples:


import java.util.*;

public class ListExample {


public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
List<String> vector = new Vector<>();

//✅ add(E e)
arrayList.add("Apple");
linkedList.add("Banana");
vector.add("Cherry");

//✅ add(int index, E element)


arrayList.add(0, "Apricot");
linkedList.add(1, "Blueberry");
vector.add(1, "Coconut");

CodeWithSubhsam
■ Click here to access the resource
//✅ remove(Object o)
arrayList.remove("Apple");
linkedList.remove("Banana");
vector.remove("Cherry");

//✅ remove(int index)


arrayList.remove(0);
linkedList.remove(0);
vector.remove(0);

//✅ get(int index)


arrayList.add("Orange");
System.out.println("Get: " + arrayList.get(0)); // Orange

//✅ set(int index, E element)


arrayList.set(0, "Mango"); // Replaces Orange with Mango

//✅ contains(Object o)
System.out.println(arrayList.contains("Mango")); // true

//✅ size()
System.out.println(arrayList.size()); // 1

//✅ isEmpty()
System.out.println(linkedList.isEmpty()); // true

//✅ clear()
vector.clear();

//✅ iterator()
arrayList.add("Kiwi");
arrayList.add("Grapes");
Iterator<String> itr = arrayList.iterator();
while (itr.hasNext()) {
System.out.println("Iterator: " + itr.next());
}
}
}

CodeWithSubhsam
■ Click here to access the resource
🔧 Important Methods of List: ✅ Stack in Java
📘 Definition:
A Stack is a Last-In-First-Out (LIFO) data structure — the last element added is the
first one to be removed. Java provides Stack as a class in the java.util package.

It extends the Vector class and adds methods to support stack operations like push,
pop, peek, etc.

🔧 Key Methods in Stack:


Method Description

push(E e) Adds element to the top of the stack

pop() Removes and returns the top element

peek() Returns the top element without


removing it

isEmpty() Checks if the stack is empty

search(Object Returns 1-based position of element


o) from top

💡 Internally:
●​ Stack is based on Vector, so it is synchronized (thread-safe).
●​ Slower than Deque for modern use cases.

💻 Code Example:

CodeWithSubhsam
■ Click here to access the resource
import java.util.Stack;

public class StackExample {

​ public static void main(String[] args) {

​ Stack<String> stack = new Stack<>();

​ // Push elements

​ stack.push("Java");

​ stack.push("Python");

​ stack.push("C++");

​ System.out.println("Stack: " + stack); // [Java, Python, C++]

​ // Peek (top element)

​ System.out.println("Top: " + stack.peek()); // C++

​ // Pop (remove top)

​ stack.pop();

​ System.out.println("After pop: " + stack); // [Java, Python]

​ // Check empty

​ System.out.println("Is empty? " + stack.isEmpty()); // false

CodeWithSubhsam
■ Click here to access the resource
​ // Search

​ int pos = stack.search("Java"); // 2 (from top)

​ System.out.println("Java found at: " + pos);

​ }

🧾 Output:
Stack: [Java, Python, C++]

Top: C++

After pop: [Java, Python]

Is empty? false

Java found at: 2

💡 Since Stack extends Vector, all methods of Vector are also


available in Stack.

🔁 That means you can use:


🔹 add(), remove(), get(), set(), size() etc.
along with:

🔹 push(), pop(), peek(), isEmpty(), search() from Stack


📌 Why use Stack if we already have Vector?

CodeWithSubhsam
■ Click here to access the resource
Because Stack gives extra LIFO methods (push, pop, etc.) built on top of Vector.

✅ Set Interface in Java


📘 Definition:
The Set interface in Java is a part of the Collection framework and represents a
collection of unique elements, i.e., no duplicates allowed.

It is found in the package:

import java.util.Set;

🔑 Key Features of Set:


Feature Description

Duplicates ❌ Not allowed


Order ❌ Not guaranteed (in
HashSet)

Allows null ✅ Yes (only one null allowed)


Implementatio HashSet, LinkedHashSet,
ns TreeSet

🔰 Common Set Implementations:

CodeWithSubhsam
■ Click here to access the resource
Type Ordered Sorted Duplicate Thread-saf
? ? s? e?

HashSet ❌ No ❌ No ❌ No ❌ No
LinkedHashS ✅ Yes ❌ No ❌ No ❌ No
et

TreeSet ✅ Yes ✅ Yes ❌ No ❌ No

✅ the common methods of the Set interface are available in all its implementations:
Method Available in HashSet LinkedHashS TreeSet
et

add(E e) ✅ Yes ✅ Yes ✅ Yes


remove(E e) ✅ Yes ✅ Yes ✅ Yes
contains(E ✅ Yes ✅ Yes ✅ Yes
e)

size() ✅ Yes ✅ Yes ✅ Yes


isEmpty() ✅ Yes ✅ Yes ✅ Yes
clear() ✅ Yes ✅ Yes ✅ Yes
iterator() ✅ Yes ✅ Yes ✅ Yes

CodeWithSubhsam
■ Click here to access the resource
📌 Note:
●​ These methods are declared in the Set interface.
●​ All three classes (HashSet, LinkedHashSet, TreeSet) implement the Set
interface, so they must provide definitions for these methods.

💻 Code Example using HashSet:


import java.util.*;

public class SetExample {

​ public static void main(String[] args) {

​ Set<String> set = new HashSet<>();

​ // Add elements

​ set.add("Java");

​ set.add("Python");

​ set.add("Java"); // Duplicate, will be ignored

​ set.add("C++");

​ // Display Set

​ System.out.println("Set: " + set); // Unordered, unique only

​ // Check for element

​ System.out.println("Contains Java? " + set.contains("Java")); // true

CodeWithSubhsam
■ Click here to access the resource
​ // Remove element

​ set.remove("Python");

​ // Iterate using for-each

​ for (String s : set) {

​ System.out.println("Element: " + s);

​ }

​ // Size

​ System.out.println("Size: " + set.size());

​ }

🧾 Output (Order may vary):


Set: [C++, Java, Python]

Contains Java? true

Element: C++

Element: Java

Size: 2

✅ Queue Interface in Java


CodeWithSubhsam
■ Click here to access the resource
📘 Definition:
The Queue interface represents a First-In-First-Out (FIFO) data structure — elements
are added at the rear (tail) and removed from the front (head).

It is part of the Collection Framework, present in:

import java.util.Queue;

🔑 Key Features of Queue:


Feature Description

Order ✅ Yes (insertion order maintained)


Duplicates ✅ Yes
allowed

FIFO ✅ Yes (First In, First Out)


Null allowed ❌ Not always (depends on
implementation)

🔰 Common Implementations of Queue:


Class Ordered Blocking Notes
? ?

LinkedList ✅ Yes ❌ No Can be used as a queue

PriorityQueu ❌ No ❌ No Elements ordered by


e priority

CodeWithSubhsam
■ Click here to access the resource
ArrayDeque ✅ Yes ❌ No Fastest queue
(non-blocking)

🔧 Common Queue Methods:


Method Description

add(E e) Adds element, throws exception if full

offer(E Adds element, returns false if full


e)

remove( Removes head, throws exception if


) empty

poll() Removes head, returns null if empty

element Returns head, throws exception if


() empty

peek() Returns head, returns null if empty

✅ 📌 offer() vs add():
●​ add() throws IllegalStateException if capacity is full
●​ offer() returns false if full — safer for bounded queues

💻 Example Code using LinkedList as Queue:


import java.util.*;

CodeWithSubhsam
■ Click here to access the resource
public class QueueExample {

​ public static void main(String[] args) {

​ Queue<String> queue = new LinkedList<>();

​ // Add elements

​ queue.offer("Java");

​ queue.offer("Python");

​ queue.offer("C++");

​ System.out.println("Queue: " + queue); // FIFO order

​ // Peek at head

​ System.out.println("Head: " + queue.peek()); // Java

​ // Remove head

​ queue.poll();

​ System.out.println("After poll: " + queue); // Python, C++

​ }

🧾 Output:
Queue: [Java, Python, C++]

CodeWithSubhsam
■ Click here to access the resource
Head: Java

After poll: [Python, C++]

✅ When to Use Queue?


Use Queue when:

●​ You need FIFO ordering (e.g., customer line, task scheduling)

✅ Map Interface in Java


📘 Definition:
The Map interface in Java represents a collection of key-value pairs, where:

●​ Each key is unique


●​ Each key maps to exactly one value

📦 Package:
import java.util.Map;

🔑 Key Features of Map:


Feature Description

Stores pairs ✅ Key → Value

CodeWithSubhsam
■ Click here to access the resource
Duplicate keys ❌ Not allowed
Duplicate values ✅ Allowed
Key order Depends on implementation
maintained?

Null keys/values ✅ One null key, multiple null values (in


HashMap)

🔰 Common Implementations of Map:


Implementatio Ordered? Sorted Thread-saf Notes
n ? e?

HashMap ❌ Unordered ❌ No ❌ No Fast, general-purpose map

LinkedHashMa ✅ Insertion ❌ No ❌ No Maintains order of insertion


p Order

TreeMap ✅ Sorted by ✅ Yes ❌ No Keys sorted using natural


keys order

Hashtable ❌ Unordered ❌ No ✅ Yes Legacy, synchronized map

🔧 Common Methods in Map:


Method Description

put(K key, V value) Adds key-value pair

CodeWithSubhsam
■ Click here to access the resource
get(Object key) Returns value for given key

remove(Object key) Removes key and its value

containsKey(Object Checks if key exists


key)

containsValue(Object Checks if value exists


val)

keySet() Returns Set of all keys

values() Returns Collection of all values

entrySet() Returns Set of key-value pairs


(entries)

isEmpty() Checks if map is empty

size() Returns total number of entries

clear() Removes all key-value pairs

💻 Java Example using HashMap:


import java.util.*;

public class MapExample {

​ public static void main(String[] args) {

​ Map<Integer, String> map = new HashMap<>();

CodeWithSubhsam
■ Click here to access the resource
​ // Put key-value pairs

​ map.put(101, "Java");

​ map.put(102, "Python");

​ map.put(103, "C++");

​ // Overwrite value at existing key

​ map.put(102, "Kotlin");

​ // Get value

​ System.out.println("Key 102: " + map.get(102)); // Kotlin

​ // Print entire map

​ System.out.println("Map: " + map);

​ // Check key existence

​ System.out.println("Contains key 101? " + map.containsKey(101));

​ // Loop through map

​ for (Map.Entry<Integer, String> entry : map.entrySet()) {

​ System.out.println(entry.getKey() + " → " + entry.getValue());

​ }

​ }

CodeWithSubhsam
■ Click here to access the resource
}

🧾 Output:
Key 102: Kotlin

Map: {101=Java, 102=Kotlin, 103=C++}

Contains key 101? true

101 → Java

102 → Kotlin

103 → C++

✅ What is Sorting?
📘 Definition:​
Sorting is the process of arranging elements in a specific order, typically:

🔼 Ascending (low to high)


🔽 Descending (high to low)
●​
●​

✅ Java Supports Sorting Through:


1.​ Collections.sort() → for List
2.​ Arrays.sort() → for arrays
3.​ Comparator / Comparable → for custom sorting

✅ 1. Sorting a List (Strings, Integers)


💻 Example: Ascending Order
import java.util.*;

CodeWithSubhsam
■ Click here to access the resource
public class SortList {

​ public static void main(String[] args) {

​ List<String> list = new ArrayList<>();

​ list.add("Java");

​ list.add("Python");

​ list.add("C++");

​ Collections.sort(list); // Ascending

​ System.out.println("Sorted List: " + list);

​ }

Output:

Sorted List: [C++, Java, Python]

💻 Example: Descending Order


Collections.sort(list, Collections.reverseOrder());

System.out.println("Descending: " + list);

✅ 2. Sorting an Array
int[] arr = {5, 2, 8, 1};

Arrays.sort(arr); // Ascending

CodeWithSubhsam
■ Click here to access the resource
System.out.println(Arrays.toString(arr)); // [1, 2, 5, 8]

What is Comparator in Java?


📘 Definition:
The Comparator interface in Java is used to define custom sorting logic
outside the class.​
comparator is an interface we don’t make the object direct we make override method

Or we can use anonymous class or lambda

Comparator<T> is a functional interface used to define custom sorting logic outside


the class.

public interface Comparator<T> {

​ int compare(T o1, T o2);

🔍 Key Points:
Feature Detail

Type Interface

CodeWithSubhsam
■ Click here to access the resource
Functional? ✅ Yes (only 1 abstract method)
Method compare(T o1, T o2)
name

Used for Custom sorting


(ascending/descending)

Package java.util.Comparator

📌 Key Method:
int compare(T o1, T o2);

●​ Returns -1 if o1 < o2
●​ Returns 0 if o1 == o2
●​ Returns 1 if o1 > o2

🔍 Meaning:
This comparator compares two integers based on their last digit (i % 10).

✅ Full Java Code:


import java.util.*;

public class Demo {

​ // Custom comparator: sort by last digit

​ // anonymous class or lambda

CodeWithSubhsam
■ Click here to access the resource
​ Comparator<Integer> com = new Comparator<Integer>() {

​ public int compare(Integer i, Integer j) {

​ // [43,31,72,29]

​ if (i % 10 > j % 10)

​ return 1;

​ else

​ return -1;

​ }

​ };

​ public static void main(String[] args) {

​ List<Integer> nums = new ArrayList<>();

​ nums.add(43); // last digit = 3

​ nums.add(31); // last digit = 1

​ nums.add(72); // last digit = 2

​ nums.add(29); // last digit = 9

​ // Sort using custom comparator

​ // when we use only Coll.sort(nums)= ascending order

​ // com = comparator

​ Collections.sort(nums, com);

​ // Output

CodeWithSubhsam
■ Click here to access the resource
​ System.out.println(nums);

​ }

🧾 Output:
[31, 72, 43, 29]

💡 Explanation:
It sorts numbers based on last digit:

●​ 31 → 1
●​ 72 → 2
●​ 43 → 3
●​ 29 → 9

Sorted in ascending order of last digit → ✅

✅ Comparable in Java
📘 Definition:
Comparable is an interface used to define the natural/default sorting order of objects.

●​ You use it inside the class that you want to sort.


●​ You must override the compareTo() method.

🔑 Method:
public int compareTo(T o);

It returns:

CodeWithSubhsam
■ Click here to access the resource
●​ 0 → if both objects are equal
●​ < 0 → if current object is less than o
●​ > 0 → if current object is greater than o

✅ Example Use Case:


Suppose we want to sort students by roll number in ascending order.

💻 Easy Code Example:


✅ 1. Student.java (the class file)
public class Student implements Comparable<Student> {

​ int roll;

​ String name;

// Saurabh.compareTo(Amit)​
→// this.roll = 103, s.roll = 101

​ public Student(int roll, String name) {

​ this.roll = roll;

​ this.name = name;

​ }

​ // Sort by roll number (ascending)

​ public int compareTo(Student s) {

​ return this.roll - s.roll;

​ }

CodeWithSubhsam
■ Click here to access the resource
​ public String toString() {

​ return roll + " - " + name;

​ }

✅ 2. ComparableExample.java (the main file)


import java.util.*;

public class ComparableExample {

​ public static void main(String[] args) {

​ List<Student> list = new ArrayList<>();

​ list.add(new Student(103, "Saurabh"));

​ list.add(new Student(101, "Amit"));

​ list.add(new Student(102, "Rahul"));

​ Collections.sort(list); // uses compareTo()

​ for (Student s : list)

​ System.out.println(s);

​ }

🧾 Output:

CodeWithSubhsam
■ Click here to access the resource
101 - Amit

102 - Rahul

103 – Saurabh

CodeWithSubhsam
■ Click here to access the resource

You might also like