0% found this document useful (0 votes)
6 views17 pages

Collection Framework Notes

Uploaded by

only4study001
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)
6 views17 pages

Collection Framework Notes

Uploaded by

only4study001
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

Collection Framework[Important

only]

Collections Framework

1. What is the Collections Framework?

Concept
The Collections Framework in Java is a unified architecture for storing, retrieving,
and manipulating collections of data. It consists of:

1. Interfaces: Define operations (e.g., List , Set , Map ).

2. Classes: Implement the interfaces (e.g., ArrayList , HashMap ).

3. Algorithms: Provide utility methods for collections (e.g., sorting, searching).

Real-World Example
A List can represent a queue of people.

A Map can store student IDs and their names.

Core Interfaces and Classes


2. List, Set, SortedSet, Queue, Deque, and Map

Concept
List: Ordered collection (e.g., ArrayList , LinkedList ).

Set: Unordered collection of unique elements (e.g., HashSet , TreeSet ).

SortedSet: A Set that maintains ascending order ( TreeSet ).

Queue: FIFO (First In, First Out) data structure (e.g., PriorityQueue ).

Collection Framework[Important only] 1


Deque: Double-ended queue allowing insertions/removals from both ends
( ArrayDeque ).

Map: Key-value pairs (e.g., HashMap , TreeMap ).

Example

import java.util.*;

public class CoreInterfacesDemo {


public static void main(String[] args) {
// List example
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println("List: " + names);

// Set example
Set<Integer> uniqueNumbers = new HashSet<>();
uniqueNumbers.add(10);
uniqueNumbers.add(20);
uniqueNumbers.add(10); // Duplicate, ignored
System.out.println("Set: " + uniqueNumbers);

// Map example
Map<Integer, String> idToName = new HashMap<>();
idToName.put(1, "Alice");
idToName.put(2, "Bob");
System.out.println("Map: " + idToName);
}
}

3. ArrayList and LinkedList

Collection Framework[Important only] 2


Concept
ArrayList: Dynamic array; fast for access but slower for insertions.

LinkedList: Doubly-linked list; fast for insertions but slower for access.

Example

import java.util.*;

public class ListDemo {


public static void main(String[] args) {
// ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
System.out.println("ArrayList: " + arrayList);

// LinkedList
List<String> linkedList = new LinkedList<>();
linkedList.add("X");
linkedList.add("Y");
System.out.println("LinkedList: " + linkedList);
}
}

Explanation
ArrayList: Elements are stored in a resizable array.

LinkedList: Each element points to the next and previous elements.

4. HashSet, LinkedHashSet, TreeSet

Concept

Collection Framework[Important only] 3


HashSet: Unordered, unique elements.

LinkedHashSet: Ordered insertion, unique elements.

TreeSet: Sorted, unique elements.

Example

import java.util.*;

public class SetDemo {


public static void main(String[] args) {
// HashSet
Set<String> hashSet = new HashSet<>();
hashSet.add("A");
hashSet.add("B");
hashSet.add("A"); // Duplicate ignored
System.out.println("HashSet: " + hashSet);

// LinkedHashSet
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("A");
linkedHashSet.add("B");
System.out.println("LinkedHashSet: " + linkedHashSe
t);

// TreeSet
Set<String> treeSet = new TreeSet<>();
treeSet.add("B");
treeSet.add("A");
System.out.println("TreeSet: " + treeSet); // Sorted
}
}

Collection Framework[Important only] 4


5. Queue and Deque

Concept
Queue: FIFO data structure.

Deque: Allows operations at both ends.

Example

import java.util.*;

public class QueueDemo {


public static void main(String[] args) {
// Queue
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println("Queue: " + queue);

// Deque
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(10);
deque.addLast(20);
System.out.println("Deque: " + deque);
}
}

6. Map and Related Classes

Concept
HashMap: Unordered key-value pairs.

LinkedHashMap: Ordered by insertion.

Collection Framework[Important only] 5


TreeMap: Sorted by keys.

Example

import java.util.*;

public class MapDemo {


public static void main(String[] args) {
// HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
System.out.println("HashMap: " + hashMap);

// TreeMap
Map<Integer, String> treeMap = new TreeMap<>();
treeMap.put(2, "B");
treeMap.put(1, "A");
System.out.println("TreeMap: " + treeMap); // Sorted
by key
}
}

7. Comparator and RandomAccess Interfaces

Concept
Comparator: Defines custom sorting.

RandomAccess: Marker interface for fast random access in lists.

Example

Collection Framework[Important only] 6


import java.util.*;

public class ComparatorDemo {


public static void main(String[] args) {
List<String> list = Arrays.asList("Bob", "Alice", "Ch
arlie");

list.sort((s1, s2) -> s1.length() - s2.length()); //


Sort by length
System.out.println("Sorted by length: " + list);
}
}

8. Abstract Collections

Concept
Abstract collections provide skeletal implementations of collection interfaces (e.g.,
AbstractList , AbstractSet ).

1. Traversing Collections
Concept
Traversing a collection means iterating through its elements. Java provides
multiple ways to traverse collections:

1. For-each Loop: Simplest way to iterate over elements.

2. Iterator: Provides a generic way to traverse collections.

3. ListIterator: A bidirectional iterator for lists.

4. Enumeration: Legacy traversal for older classes like Vector .

5. Streams API: Functional-style traversal introduced in Java 8.

Collection Framework[Important only] 7


Examples

For-each Loop

import java.util.*;

public class ForEachExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "C
harlie");

for (String name : names) {


System.out.println(name);
}
}
}

Iterator

import java.util.*;

public class IteratorExample {


public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

Iterator<String> iterator = names.iterator();


while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}

Collection Framework[Important only] 8


}

ListIterator

import java.util.*;

public class ListIteratorExample {


public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

ListIterator<String> listIterator = names.listIterato


r();

// Forward Traversal
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}

// Backward Traversal
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}

Streams API

import java.util.*;

Collection Framework[Important only] 9


public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "C
harlie");

names.stream().forEach(name -> System.out.println(nam


e));
}
}

2. Sorting Collections
Concept
Sorting arranges the elements of a collection in a specific order (natural or
custom). Java provides:

1. Natural Sorting: Uses the natural ordering of elements (e.g., ascending for
numbers).

2. Custom Sorting: Allows defining custom order using Comparator .

Examples

Natural Sorting
Collections.sort() is used to sort a list in ascending order by default.

import java.util.*;

public class NaturalSortingExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 3, 8, 1);

Collections.sort(numbers); // Ascending order

Collection Framework[Important only] 10


System.out.println("Sorted List: " + numbers);
}
}

Sorting with Comparable


Comparable is an interface that allows objects of a class to be compared to one
another. It is used to define the natural order for custom objects.

import java.util.*;

class Student implements Comparable<Student> {


String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public int compareTo(Student other) {
return this.age - other.age; // Ascending by age
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class ComparableExample {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();

Collection Framework[Important only] 11


students.add(new Student("Alice", 20));
students.add(new Student("Bob", 18));
students.add(new Student("Charlie", 22));

Collections.sort(students);
System.out.println("Sorted by Age: " + students);
}
}

3. Custom Sorting
Concept
Custom sorting is achieved using the Comparator interface. This allows defining
multiple sorting criteria for a collection.

Example
Sorting students by name in descending order using a Comparator .

import java.util.*;

class Student {
String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return name + " (" + age + ")";

Collection Framework[Important only] 12


}
}

public class CustomSortingExample {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 18));
students.add(new Student("Charlie", 22));

// Custom sorting by name (descending)


students.sort((s1, s2) -> s2.name.compareTo(s1.nam
e));

System.out.println("Sorted by Name (Descending): " +


students);

// Custom sorting by age (ascending)


students.sort(Comparator.comparingInt(s -> s.age));
System.out.println("Sorted by Age (Ascending): " + st
udents);
}
}

Using Streams for Custom Sorting


With Java 8, the Stream API provides an elegant way to sort collections.

Example

import java.util.*;
import java.util.stream.Collectors;

Collection Framework[Important only] 13


class Student {
String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class StreamSortingExample {


public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 20),
new Student("Bob", 18),
new Student("Charlie", 22)
);

// Sorting by name
List<Student> sortedByName = students.stream()
.sorted(Comparator.comparing(s -> s.name))
.collect(Collectors.toList());
System.out.println("Sorted by Name: " + sortedByNam
e);

// Sorting by age (descending)


List<Student> sortedByAgeDescending = students.stream
()
.sorted((s1, s2) -> Integer.compare(s2.age, s1.ag
e))
.collect(Collectors.toList());

Collection Framework[Important only] 14


System.out.println("Sorted by Age (Descending): " + s
ortedByAgeDescending);
}
}

Collection Framework Interfaces


Implementation
Interface/Class Description Key Features
Classes

Basic operations: add ,


Root interface for all
Collection remove , size , isEmpty , -
collection types.
clear .

- Indexed access to
Ordered collection ArrayList ,
elements- Allows
List that allows duplicate LinkedList ,
duplicates- Preserves
elements. Vector , Stack
insertion order

- Does not allow


duplicates- Unordered HashSet ,
Collection of unique
Set (except for LinkedHashSet ,
elements.
LinkedHashSet and TreeSet , EnumSet
TreeSet )

A Set with sorted - Maintains elements in


SortedSet TreeSet
order. natural or custom order

- Used for holding


elements before LinkedList ,
FIFO (First In, First
Queue processing- May allow PriorityQueue ,
Out) collection.
duplicates- Elements ArrayDeque
processed sequentially

Double-ended queue, - Can act as a queue or


supports insertion and stack- Can hold null ArrayDeque ,
Deque
removal from both elements (except LinkedList
ends. ArrayDeque )

Map Key-value pairs; keys - Allows null keys and HashMap ,


must be unique. values (except TreeMap )- LinkedHashMap ,

Collection Framework[Important only] 15


Efficient retrieval by key TreeMap

A Map with sorted - Maintains natural or


SortedMap TreeMap
keys. custom order for keys

Extends SortedMap - Additional methods like


NavigableMap with navigation floorKey , ceilingKey , TreeMap

methods. higherKey , etc.

Important Classes in the Collections Framework


Class Description Key Features

- Fast random access- Slow


Resizable array
ArrayList insertion/removal in the middle-
implementation of List .
Allows duplicates

Doubly-linked list - Fast insertion and deletion- Slower


LinkedList implementation of List and random access- Can act as Queue or
Deque . Deque

Implements Set using a hash - Unordered- Allows one null


HashSet
table. element- Fast lookups

Extends HashSet with - Maintains insertion order- Slower


LinkedHashSet
predictable iteration order. than HashSet

Implements SortedSet using a


TreeSet - Sorted elements- No null elements
red-black tree.

Implements Queue with - Not necessarily FIFO- Uses natural


PriorityQueue
priority ordering. or custom ordering

- Resizable array- Fast insertion and


ArrayDeque Implements Deque .
deletion- Does not allow null elements

Implements Map using a hash - Unordered- Allows one null key and
HashMap
table. multiple null values

Extends HashMap with


LinkedHashMap - Maintains insertion order
predictable iteration order.

Implements NavigableMap - Sorted keys- Does not allow null


TreeMap
using a red-black tree. keys

Collection Framework[Important only] 16


Implements Map using
IdentityHashMap reference equality instead of - Keys compared using ==
equals() .

Implements Map with keys that - Keys are garbage-collected when


WeakHashMap
are weak references. no longer in use

Map with keys restricted to an - Keys must be enum constants- Very


EnumMap
enumeration type. efficient

Synchronized resizable array


Vector - Legacy class- Thread-safe
implementation of List .

Extends Vector to provide a - Legacy class- Methods: push ,


Stack
LIFO (Last In, First Out) stack. pop , peek

Key Functional Interfaces


Interface Description Key Features

Used to define custom sorting for - Functional interface-


Comparator
objects. Method: compare()

Base interface for traversing


Iterable - Method: iterator()
collections.

- Methods: hasNext() ,
Iterator Allows forward traversal of a collection.
next() , remove()

- Methods: hasPrevious() ,
ListIterator Bi-directional iterator for List .
previous() , add()

Marker interface for fast random - Implemented by ArrayList


RandomAccess
access in List implementations. and Vector

Collection Framework[Important only] 17

You might also like