0% found this document useful (0 votes)
0 views25 pages

Java Collections

Java Collections is a framework that provides classes and interfaces for storing and managing groups of objects dynamically. It includes various data structures like List, Set, Queue, and Map, each with unique features such as allowing duplicates or maintaining order. Additionally, assertions in Java are used for debugging assumptions made during development, throwing an error if the assumption is false.

Uploaded by

lord.sharukesh
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)
0 views25 pages

Java Collections

Java Collections is a framework that provides classes and interfaces for storing and managing groups of objects dynamically. It includes various data structures like List, Set, Queue, and Map, each with unique features such as allowing duplicates or maintaining order. Additionally, assertions in Java are used for debugging assumptions made during development, throwing an error if the assumption is false.

Uploaded by

lord.sharukesh
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

Collections in Java

What are Collections in Java?

❑ Java Collections = A framework (set of classes + interfaces) used to store & manage groups
of objects efficiently.
❑ Think of Collections as advanced containers that can grow and shrink dynamically (unlike
arrays).
Why Do We Need Collections?

Arrays Collections
Fixed size Dynamic size (grow/shrink)
Only same data type Can store any object type
Hard to insert/delete Easy to add, remove, search, sort
No built-in methods Many ready-made methods
Interface Key Feature Allows Duplicates? Common Classes
List Maintains order Yes ArrayList, LinkedList, Vector

Set No duplicates No HashSet, TreeSet, LinkedHashSet

Queue First-In-First-Out Yes PriorityQueue, ArrayDeque

HashMap, TreeMap,
Map Stores Key → Value Keys (No) Values (Yes)
LinkedHashMap
What is ArrayList?
ArrayList is a dynamic array. It can grow and shrink when we add or remove elements.

Example:
List<String> names = new ArrayList<>();
[Link](“Tom");
[Link](“Reena");
[Link](names)

Feature ArrayList Behavior


Size Grows automatically
Order Maintains insertion order
Duplicates Allowed
Speed Fast access / slower insert in middle
New
Saves memory (lazy creation) + works smoothly with Streams
Improvement
LinkedList
LinkedList is a linear data structure in which elements are stored as nodes, and each node stores:
[Link]
[Link] (link) to the next node

So, elements are connected like a chain. LinkedList is good when you add or remove elements frequently, especially in
the middle.

Syntax Valid Today?


LinkedList<Type> list = new LinkedList<>(); Yes
List<Type> list = new LinkedList<>(); Yes
var list = new LinkedList<Type>(); Yes (Java 10+)

Feature Behavior
Dynamic Size Grows & shrinks automatically
Insertion/Deletion Fast (no shifting of elements)
Access by Index Slower than ArrayList
Allows duplicates Yes
Maintains Order Yes (insertion order)
❑ A Queue is a linear data structure that works on the FIFO principle:
❑ FIFO (First In First Out) → The element inserted first is removed first.
❑ In Java, Queue is an interface in the [Link] package.
We cannot create a Queue object directly — we use classes like LinkedList,
PriorityQueue, or ArrayDeque to implement it.

Java Version Syntax Explanation


Java 5 to Java 7 Queue<Type> q = new LinkedList<Type>(); Generics introduced. Both sides specify Type.
Java 7+ (Diamond
Queue<Type> q = new LinkedList<>(); Right side infers type (no need to repeat <Type>).
Operator)
Java 10+ (var Java automatically detects the data type. Cleaner
var q = new LinkedList<Type>();
keyword) code.
Features of Queue

Feature Explanation (Simple)


FIFO Order First element added is the first one removed.
Dynamic Size Queue can grow and shrink automatically.

Insert at Rear New elements are always added at the back of the queue.

Remove from Front Elements are removed from the front of the queue.

Maintains Insertion Order Elements stay in the order in which they were inserted.

Allows Duplicates Same value can appear more than once.


Cannot create object directly. Must use LinkedList, PriorityQueue, or
Queue is an Interface
ArrayDeque.

Supports Special Methods add(), peek(), poll(), remove(), isEmpty() for operations.
Set
A Set is a collection that does NOT allow duplicate elements.
It stores unique values only.
Set is an interface in [Link] package.

Type of Set Syntax (Using Interface – Recommended) Meaning


HashSet Set<Type> set = new HashSet<>(); Stores unique elements; no order maintained

LinkedHashSet Set<Type> set = new LinkedHashSet<>(); Stores unique elements; maintains insertion order
TreeSet Set<Type> set = new TreeSet<>(); Stores unique elements; keeps elements sorted
Any Set var set = new HashSet<String>(); Cleaner and shorter code (Java auto-detects type)

Feature Explanation
No Duplicates Set does not allow duplicate values.
No Indexing Elements cannot be accessed with index like list.
May or May Not Maintain Order Depends on the implementation.
Dynamic Size Grows and shrinks automatically.
Set is an Interface Must use classes like HashSet, TreeSet, LinkedHashSet.
LinkedHashSet Program
(Maintains insertion order)
TreeSet Program
(Stores elements in sorted (ascending) order)
1. Write a Java program to read N integers from the user and store them in a Set. The program should
automatically remove duplicates and print only unique numbers.

2. Write a Java program to read names of students, store them in a LinkedHashSet, and display them in the
same order they were entered, ensuring no duplicates.

3. Write a Java program to store 5 city names in a TreeSet and display them in alphabetical order.
A Map in Java is a collection that stores data in key–value pairs.
•Each key is unique
•Each key has one value
•Values can be duplicate, keys cannot
Example: Roll Number → Student Name
(Roll number is unique, but two students may share the same name)

Map Type Syntax Special Feature


HashMap Map<K, V> map = new HashMap<>(); Fast but no order
LinkedHashMap Map<K, V> map = new LinkedHashMap<>(); Maintains insertion order
TreeMap Map<K, V> map = new TreeMap<>(); Sorted by keys
var map = new HashMap<Integer, String>();
Feature Explanation
Stores Key-Value pairs Example → 101 → “Tim”
Keys cannot be duplicated Only one value per key
Values can be duplicated Two entries may have the same value
No indexing Data accessed using key, not position
Different Implementations HashMap, LinkedHashMap, TreeMap
Function Description Example
Adds a new key-value pair / Updates if key
put(key, value) [Link](101, "Tim");
exists
get(key) Returns the value of the given key [Link](101);

remove(key) Removes the entry with the given key [Link](101);

containsKey(key) Checks if a key exists [Link](101);

containsValue(value) Checks if a value exists [Link]("Tim");

size() Returns number of entries [Link]();


isEmpty() Returns true if map has no entries [Link]();
clear() Removes all entries [Link]();
keySet() Returns set of all keys [Link]();
values() Returns collection of all values [Link]();
entrySet() Returns set of all key-value pairs Used for looping
Assertion in JAVA

❑ Assertion is a statement in Java that is used to check assumptions made by the programmer during development.
- If the assumption is true, the program runs normally.
- If the assumption is false, Java throws an AssertionError.
❑ Assertion = Used for debugging, not for normal input validation.

Type Syntax Meaning


If condition is false →
Simple Assertion assert condition;
AssertionError
Assertion with Message assert condition : "Message"; Shows message if condition is false
>java -ea AssertExample
-ea means Enable Assertions.
When to Use Assertion ?
Use assert when:

❑ Checking logic conditions during development

❑ Validating something that should never be false

❑ Do not use assert:

❑ For user input validation

❑ In production applications

You might also like