0% found this document useful (0 votes)
2 views

Java Module-4

The document provides an overview of the Java Collection Framework, detailing its interfaces (List, Set, Map) and their implementations (ArrayList, HashSet, LinkedList, etc.). It explains the advantages of using collections over arrays, such as dynamic resizing, built-in sorting, and type safety through generics. Additionally, it covers key methods and examples for various collection types, including Lists, Sets, and Queues, highlighting their specific features and use cases.

Uploaded by

saikumarvenkat60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Module-4

The document provides an overview of the Java Collection Framework, detailing its interfaces (List, Set, Map) and their implementations (ArrayList, HashSet, LinkedList, etc.). It explains the advantages of using collections over arrays, such as dynamic resizing, built-in sorting, and type safety through generics. Additionally, it covers key methods and examples for various collection types, including Lists, Sets, and Queues, highlighting their specific features and use cases.

Uploaded by

saikumarvenkat60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Module 4

COLLECTION FRAMEWORK
Collection Framework: Collections Overview, Collection Interfaces - List, Set, Map, List -
ArrayList, Linked List, Vector, Set - HashSet, TreeSet, Map - HashTable, HashMap,
Accessing a collection via an Iterator, comparator, comparable.

Collection:
A Collection in Java is a framework that provides an architecture to store and
manipulate a group of objects efficiently. It includes interfaces (List, Set, Queue) and their
implementations (ArrayList, HashSet, LinkedList, etc.) to manage data dynamically.

Why is Collection Necessary?


Before Java Collections, programmers had to use arrays and manual data structures (like
LinkedLists, Stacks, etc.), which had limitations like:
Problem in Arrays Solution in Collections Example
Fixed Size → Cannot Dynamic resizing in ArrayList, List<String> list = new
grow dynamically HashSet ArrayList<>();
Manual Sorting & Built-in sorting & searching Collections.sort(list);
Searching (Collections.sort())
Slow Insert/Delete Efficient operations in List<Integer> list = new
(Shifting required) LinkedList, HashSet, Queue LinkedList<>();
Difficult Iteration (Manual Easy traversal using iterators Iterator<String> it =
looping) list.iterator();
No Type Safety (Stores Generics ensure type safety List<String> names = new
any type of data) (List<String>) ArrayList<>();

Collection Overview:
The Java Collection Framework is a set of interfaces, classes, and methods that
provide an efficient way to store, manipulate, and process groups of objects in Java. It
includes Lists, Sets, Queues, and Maps, each designed for different use cases.
Key Roles of Collections:
 Stores Multiple Objects – Unlike arrays, collections dynamically manage data.
 Provides Efficient Data Handling – Sorting, searching, insertion, and deletion are
optimized.
 Supports Different Data Structures – Includes Lists, Sets, Queues, and Maps.
 Uses Generics for Type Safety – Prevents runtime type errors (List<String> list = new
ArrayList<>();).
 Uses Utility Methods – The Collections class offers sorting, shuffling, and searching.

Collection (Interface)
Definition:
 It is the root interface of the Java Collection Framework (except for Map).
 Provides basic methods to add, remove, and manipulate objects.
 Subinterfaces: List, Set, Queue.
Key Role:
 Defines basic CRUD operations (Create, Read, Update, Delete).
 Provides methods like add(), remove(), contains(), size(), etc.
Syntax:
Collectioninterface<Type> object = new Classimplementation<>(); or
classimplementation<Type> object=new Classimplementation <>();

 Collection is an interface, so we cannot create an object of it directly.


 We use a concrete implementation class (ArrayList, HashSet, LinkedList, etc.).
 (diamond operator) is used for generics to specify the type of elements.
Key Methods in Collection Interface:
Method Description Example
add(E e) Adds an element list.add("Apple");
remove(Object o) Removes an element list.remove("Apple");
size() Returns the number of elements list.size();
contains(Object o) Checks if an element exists list.contains("Apple");
clear() Removes all elements list.clear();
isEmpty() Checks if the collection is empty list.isEmpty();

Example Implementation:
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
Collection<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println("Fruits: " + fruits); // [Apple, Banana]
fruits.remove("Apple");
System.out.println("After removal: " + fruits); // [Banana]
}
}

2️. Collections (Utility Class):


Definition:
A helper class in java.util that provides static methods to operate on collections.
Used for sorting, searching, shuffling, finding max/min, etc.
Key Role:
Provides utility functions for manipulating collections.
Syntax:
Collections.methodName(collection);

Key Methods in Collections Class:

Method Description Example


sort(List<T> list) Sorts a list in ascending Collections.sort(list);
order
reverse(List<T> list) Reverses the order of Collections.reverse(list);
elements
shuffle(List<T> list) Randomly shuffles elements Collections.shuffle(list);
binarySearch(List<T> list, T Searches an element (sorted Collections.binarySearch(list,
key) list) "Apple");
max(Collection<T> coll) Returns max element Collections.max(list);
min(Collection<T> coll) Returns min element Collections.min(list);

Example Implementation:
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
Collections.sort(numbers); // Sorts the list
System.out.println("Sorted: " + numbers); // [1, 2, 5, 8]
Collections.reverse(numbers); // Reverses order
System.out.println("Reversed: " + numbers); // [8, 5, 2, 1]
}
}
3️. Collection Framework
Definition:
 A set of interfaces and classes that provides an architecture for storing and
manipulating groups of objects efficiently.
 Includes List, Set, Queue, and Map.
Key Role:
Provides built-in data structures and algorithms for managing collections.
Components in Collection Framework:

Interface Implemented Classes Supports Indexing? Usage


List ArrayList, LinkedList, Vector, ✅ Yes Ordered collection
Stack with duplicates
Set HashSet, LinkedHashSet, ❌ No Unique elements, no
TreeSet duplicates
Queue PriorityQueue, ArrayDeque ❌ No FIFO-based
elements
Map (Not HashMap, TreeMap, ❌ No Key-value pairs
in LinkedHashMap
Collection)
What is a List in Java?
In Java, a List is an ordered collection (also known as a sequence) that allows
duplicate elements. It is part of the Java Collections Framework (JCF) and is defined by
the java.util.List interface.
Key Features of List:
 Ordered Collection → Elements maintain their insertion order.
 Allows Duplicates → You can store the same element multiple times.
 Indexed Access → Each element has an index (starting from 0).
 Resizable → Unlike arrays, List can grow or shrink dynamically.
1. ArrayList Example
An ArrayList is a dynamic array that allows fast access but slower insertions/removals
in the middle.
 Fast random access,
 Resizable array,
 Slower insert/delete in the middle
Method Description
add(E e) Adds an element to the end of the list.
add(int index, E e) Adds an element at a specific index.
get(int index) Returns the element at the specified index.
set(int index, E e) Replaces the element at the specified index.
remove(int index) Removes the element at the specified index.
remove(Object o) Removes the first occurrence of the specified object.
size() Returns the number of elements in the list.
clear() Removes all elements from the list.
isEmpty() Returns true if the list is empty.
contains(Object o) Returns true if the list contains the specified element.
indexOf(Object o) Returns the index of the first occurrence of the specified
element.
lastIndexOf(Object o) Returns the index of the last occurrence of the specified
element.
toArray() Converts the list to an array.
iterator() Returns an iterator to iterate through the list.

Example:

import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("ArrayList: " + list);
list.remove("Banana");
System.out.println("After removal: " + list);
}
}
Output:
ArrayList: [Apple, Banana, Cherry]
After removal: [Apple, Cherry]

2. LinkedList:

A LinkedList is a doubly linked list allowing fast insertions and deletions but slower random
access.

 Frequent insertions/deletions in the middle,


 Slower random access,
 Implements Deque

Method Description
addFirst(E e) Adds an element to the beginning.
addLast(E e) Adds an element to the end.
removeFirst() Removes the first element.
removeLast() Removes the last element.
getFirst() Returns the first element.
getLast() Returns the last element.

Example:
import java.util.LinkedList;
public class LinkedListExample {s
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(10);
list.add(20);
list.add(30);

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


list.addFirst(5);
list.addLast(40);
System.out.println("After modifications: " + list);
}
}
Output:
LinkedList: [10, 20, 30]
After modifications: [5, 10, 20, 30, 40]

3. Vector:
A Vector is similar to an ArrayList but is synchronized (thread-safe).
 Synchronized (Thread-safe),
 Slower performance
Example:
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<Double> vector = new Vector<>();
vector.add(1.1);
vector.add(2.2);
vector.add(3.3);
System.out.println("Vector: " + vector);
vector.remove(1); // Removes the second element
System.out.println("After removal: " + vector);
}
}
Output:
Vector: [1.1, 2.2, 3.3]
After removal: [1.1, 3.3]

4. Stack:
Extends Vector, A Stack follows the LIFO (Last In, First Out) principle.
Method Description
push(E item) Adds an element to the top of the stack (preferred over add()).
pop() Removes and returns the top element.
peek() Returns the top element without removing it.
isEmpty() Checks if the stack is empty.
search(E item) Returns the position (1-based index) of an item.
add(E item) Works like push(), but not recommended.
remove(E item) Works but not recommended because Stack is LIFO.

Example:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("First");
stack.push("Second");
stack.push("Third");
System.out.println("Stack: " + stack);
System.out.println("Popped: " + stack.pop());
System.out.println("After pop: " + stack);
System.out.println("Peek: " + stack.peek()); // Check top element
}
}

Output:
Stack: [First, Second, Third]
Popped: Third
After pop: [First, Second]
Peek: Second
2️. Set (No Duplicates, No Order):
A Set in Java is a part of the Collection Framework that represents a collection of
unique elements. It does not allow duplicate values and is mainly implemented using
HashSet, LinkedHashSet, and TreeSet.

Key Points about Set

1. No Duplicates: A Set does not allow duplicate elements.


2. Unordered (HashSet): Elements are not stored in any specific order.
3. Ordered (LinkedHashSet & TreeSet): LinkedHashSet maintains insertion order,
while TreeSet sorts elements in natural order.
4. Allows Null: A HashSet allows a single null value, whereas TreeSet does not allow
null.
5. Faster Operations: HashSet provides constant-time performance (O(1)) for basic
operations (add, remove, contains).
6. Implements Collection Interface: Set is an interface extending Collection.
7. Iterators and Streams: Can be traversed using iterators and Java 8 streams.

Features:

 Set is useful when unique elements are needed.


 HashSet is the best for performance.
 TreeSet is good when sorted order is required.
 LinkedHashSet maintains insertion order.
 Set operations like union, intersection, and difference are easily implemented.

Set Methods with Description


Method Description
add(E e) Adds the specified element to the set if it is not already present.
remove(Object o) Removes the specified element from the set if it is present.
contains(Object o) Returns true if the set contains the specified element.
size() Returns the number of elements in the set.
clear() Removes all elements from the set.
isEmpty() Returns true if the set is empty.
iterator() Returns an iterator over the elements in this set.
toArray() Returns an array containing all elements of the set.

Set Implementations and Example Programs

1. HashSet Example

 Unordered collection, does not maintain insertion order.


 Best for fast lookups (O(1) time complexity).

import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate, will not be added

// Displaying set
System.out.println("HashSet: " + set);

// Checking if an element exists


System.out.println("Contains Banana? " + set.contains("Banana"));

// Removing an element
set.remove("Cherry");

// Iterating through the set


for (String fruit : set) {
System.out.println(fruit);
}
}
}

Output:

HashSet: [Apple, Banana, Cherry]


Contains Banana? true
Apple
Banana

2. LinkedHashSet Example

Maintains insertion order.

import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();

set.add(10);
set.add(20);
set.add(30);
set.add(10); // Duplicate, ignored

System.out.println("LinkedHashSet: " + set);


}
}

Output:

LinkedHashSet: [10, 20, 30]


3. TreeSet Example

 Elements are stored in sorted order.


 Does not allow null values.

import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();

set.add(50);
set.add(10);
set.add(30);
set.add(20);

System.out.println("TreeSet (Sorted): " + set);

// Checking for specific values


System.out.println("Lowest Value: " + set.first());
System.out.println("Highest Value: " + set.last());
}
}

Output:

TreeSet (Sorted): [10, 20, 30, 50]


Lowest Value: 10
Highest Value: 50

4. Common Set Operations

import java.util.Set;
import java.util.HashSet;

public class SetOperations {


public static void main(String[] args) {
Set<String> set1 = new HashSet<>();
set1.add("A");
set1.add("B");
set1.add("C");

Set<String> set2 = new HashSet<>();


set2.add("B");
set2.add("C");
set2.add("D");

// Union (All elements from both sets)


Set<String> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
System.out.println("Union: " + unionSet);

// Intersection (Common elements)


Set<String> intersectionSet = new HashSet<>(set1);
intersectionSet.retainAll(set2);
System.out.println("Intersection: " + intersectionSet);

// Difference (Elements in set1 but not in set2)


Set<String> differenceSet = new HashSet<>(set1);
differenceSet.removeAll(set2);
System.out.println("Difference: " + differenceSet);
}
}

Output:

Union: [A, B, C, D]
Intersection: [B, C]
Difference: [A]

3️. Queue (FIFO - First In, First Out):


A Queue in Java is a part of the Collection Framework that follows the FIFO
(First-In-First-Out) principle. It represents a linear data structure where elements are
added at the end (tail) and removed from the front (head).

Key Points about Queue


1. FIFO Principle: Elements are processed in the order they were added.
2. Two Ends: Elements are added at the rear (end) and removed from the front (head).
3. Interface Implementation: The Queue interface is part of java.util and is
implemented by:
o LinkedList (Doubly Linked List-based Queue)
o PriorityQueue (Sorted order based on priority)
o ArrayDeque (Resizable array-based Queue)
4. Types of Queues:
o Normal Queue (FIFO behavior)
o Priority Queue (Elements are dequeued based on priority)
o Deque (Double-Ended Queue) (Insertion & removal from both ends)
o BlockingQueue (Thread-Safe Queue) (For concurrency scenarios)
5. Allows Null?:
o LinkedList allows null
o PriorityQueue and ArrayDeque do not allow null values.

Implementation When to Use


LinkedList When a simple FIFO queue is needed.
PriorityQueue When elements should be dequeued in a sorted order.
ArrayDeque When both stack & queue operations are needed (Deque).
BlockingQueue When thread-safe queue operations are required in concurrency.
Queue Methods with Description:
Method Description
add(E e) Inserts an element at the tail (throws exception if full).
offer(E e) Inserts an element at the tail (returns false if full).
remove() Removes the head element (throws exception if empty).
poll() Removes the head element (returns null if empty).
element() Retrieves but does not remove the head (throws exception if empty).
peek() Retrieves but does not remove the head (returns null if empty).
size() Returns the number of elements in the queue.
isEmpty() Checks if the queue is empty.
clear() Removes all elements from the queue.

Queue Implementations and Example Programs:

1. Using LinkedList as a Queue

 Implements FIFO behavior.


 Supports null elements.

import java.util.LinkedList;
import java.util.Queue;
public class LinkedListQueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();

// Adding elements
queue.add("Alice");
queue.offer("Bob");
queue.offer("Charlie");

// Displaying the queue


System.out.println("Queue: " + queue);

// Retrieving elements
System.out.println("Head: " + queue.peek());

// Removing elements
queue.poll(); // Removes "Alice"
System.out.println("Queue after poll: " + queue);
}
}

Output:

Queue: [Alice, Bob, Charlie]


Head: Alice
Queue after poll: [Bob, Charlie]

2. PriorityQueue Example
 Sorted order (natural order or custom comparator).
 Does not allow null values.

import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();

pq.add(30);
pq.add(10);
pq.add(20);

System.out.println("PriorityQueue: " + pq);

// Polling (removing elements in sorted order)


System.out.println("Removed: " + pq.poll());
System.out.println("PriorityQueue after poll: " + pq);
}
}

Output:

PriorityQueue: [10, 30, 20]


Removed: 10
PriorityQueue after poll: [20, 30]

3. ArrayDeque (Double-Ended Queue)

 Faster than LinkedList.


 No capacity restriction (resizable).
 Does not allow null values.

import java.util.ArrayDeque;
import java.util.Queue;
public class ArrayDequeExample {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();

queue.offer("One");
queue.offer("Two");
queue.offer("Three");

System.out.println("Queue: " + queue);


System.out.println("Head Element: " + queue.peek());

queue.poll(); // Removes "One"


System.out.println("Queue after poll: " + queue);
}
}
Output:

Queue: [One, Two, Three]


Head Element: One
Queue after poll: [Two, Three]

4. Common Queue Operations

import java.util.LinkedList;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();

// Adding elements
queue.offer(5);
queue.offer(10);
queue.offer(15);

System.out.println("Queue: " + queue);

// Checking front element


System.out.println("Front: " + queue.peek());

// Removing elements
queue.poll();
System.out.println("Queue after poll: " + queue);

// Checking size
System.out.println("Queue size: " + queue.size());
}
}

Output:

Queue: [5, 10, 15]


Front: 5
Queue after poll: [10, 15]
Queue size: 2

4️. Map (Key-Value Pairs):


A Map in Java is a part of the Collection Framework that stores key-value pairs.
Unlike other collection types (List, Set), a Map does not allow duplicate keys, but values can
be duplicated.
Key Points about Map:
 FIFO Principle: Elements are processed in the order they were added.
 Two Ends: Elements are added at the rear (end) and removed from the front (head).
 Interface Implementation: The Queue interface is part of java.util and is
implemented by:
 LinkedList (Doubly Linked List-based Queue)
 PriorityQueue (Sorted order based on priority)
 ArrayDeque (Resizable array-based Queue)
 Types of Queues:
 Normal Queue (FIFO behavior)
 Priority Queue (Elements are dequeued based on priority)
 Deque (Double-Ended Queue) (Insertion & removal from both ends)
 BlockingQueue (Thread-Safe Queue) (For concurrency scenarios)
 Allows Null?:
 LinkedList allows null
 PriorityQueue and ArrayDeque do not allow null values.
Map Methods with Description:
Method Description
add(E e) Inserts an element at the tail (throws exception if full).
offer(E e) Inserts an element at the tail (returns false if full).
remove() Removes the head element (throws exception if empty).
poll() Removes the head element (returns null if empty).
element() Retrieves but does not remove the head (throws exception if empty).
peek() Retrieves but does not remove the head (returns null if empty).
size() Returns the number of elements in the queue.
isEmpty() Checks if the queue is empty.
clear() Removes all elements from the queue.

Map Implementations and Example Programs


1. HashMap Example:
Unordered storage, fast retrieval.
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();

// Adding key-value pairs


map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");

// Retrieving values
System.out.println("Value for key 2: " + map.get(2));
// Iterating over a map
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

// Checking if a key exists


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

// Removing an entry
map.remove(1);
System.out.println("After removal: " + map);
}
}
Output:
Value for key 2: Banana
Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Cherry
Contains key 3? true
After removal: {2=Banana, 3=Cherry}
2. LinkedHashMap Example:
Maintains insertion order.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new LinkedHashMap<>();

map.put("John", 25);
map.put("Alice", 30);
map.put("Bob", 22);

System.out.println("LinkedHashMap: " + map);


}
}
Output:
LinkedHashMap: {John=25, Alice=30, Bob=22}

3. TreeMap Example
Sorted order based on keys.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();

map.put(100, "A");
map.put(50, "B");
map.put(150, "C");

System.out.println("Sorted TreeMap: " + map);

// Checking first and last key


System.out.println("First Key: " + map.firstKey());
System.out.println("Last Key: " + map.lastKey());
}
}
Output:
Sorted TreeMap: {50=B, 100=A, 150=C}
First Key: 50
Last Key: 150

4. Common Map Operations


import java.util.HashMap;
import java.util.Map;

public class MapOperations {


public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
// Adding entries
scores.put("Math", 90);
scores.put("English", 85);
scores.put("Science", 92);

System.out.println("Scores: " + scores);

// Checking for a specific key


System.out.println("Contains Science? " + scores.containsKey("Science"));

// Getting all keys


System.out.println("Subjects: " + scores.keySet());

// Getting all values


System.out.println("Marks: " + scores.values());

// Updating a value
scores.put("English", 88);
System.out.println("Updated Scores: " + scores);
}
}
Output:
Scores: {Math=90, English=85, Science=92}
Contains Science? true
Subjects: [Math, English, Science]
Marks: [90, 85, 92]
Updated Scores: {Math=90, English=88, Science=92}

Iterator in Java
An Iterator in Java is an interface in the java.util package that provides a way to
traverse elements of a collection one by one without exposing its underlying structure. It is
mainly used with Collection Framework classes like ArrayList, HashSet, LinkedList, etc.
Syntax
Iterator<Type> iterator = collection.iterator();

Methods of Iterator:

Method Description
boolean hasNext() Returns true if the iteration has more elements.
Type next() Returns the next element in the iteration.
void remove() Removes the last element returned by next(). (Optional operation)

Example: Using Iterator in Java:


import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
// Creating a list
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Getting an iterator for the list


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

// Iterating through the list


System.out.println("Fruits List:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

// Removing an element using iterator


iterator = fruits.iterator(); // Reinitialize iterator
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.equals("Banana")) {
iterator.remove(); // Remove "Banana"
}
}

System.out.println("Updated List: " + fruits);


}
}
Output:
Fruits List:
Apple
Banana
Cherry
Updated List: [Apple, Cherry]

1. Comparable (Natural Ordering):


 It is used to define the default sorting order Collections.sort() of objects.
 A class implements the Comparable<T> interface and overrides the compareTo(T o)
method.
 Sorting is based on a single field.
Syntax/Structure:
class ClassName implements Comparable<ClassName> {
public int compareTo(ClassName other) {
return Integer.compare(this.someField, other.someField);
}
// Return negative if this < other
// Return zero if this == other
// Return positive if this > other
}
}
Example: compareTo() in Sorting

import java.util.*;
class Employee implements Comparable<Employee> {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
// Sorting by ID (Natural Order)
@Override
public int compareTo(Employee other) {
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
}
public class ComparableExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(103, "Alice", 50000));
employees.add(new Employee(101, "Bob", 70000));
employees.add(new Employee(102, "Charlie", 60000));

Collections.sort(employees); // Uses compareTo()


System.out.println("Sorted by ID:\n" + employees);
}
}
Output

Sorted by ID:
[ID: 101, Name: Bob, Salary: 70000.0, ID: 102, Name: Charlie, Salary: 60000.0, ID: 103,
Name: Alice, Salary: 50000.0]

2. Comparator (Custom Ordering):


 It is used to define multiple sorting criteria dynamically.
 We implement Comparator<T> and override compare(T o1, T o2).
 Sorting can be done based on multiple fields dynamically.
Syntax/Structure:
class ClassNameComparator implements Comparator<ClassName> {
@Override
public int compare(ClassName o1, ClassName o2) {
return obj1.someField.compareTo(obj2.someField);
}
// Return negative if o1 < o2
// Return zero if o1 == o2
// Return positive if o1 > o2
}

Example: Sorting by Name & Salary Using compare()

import java.util.*;
// Employee class without Comparable
class Employee {
int id;
String name;
double salary;

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

@Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
}

// Comparator for sorting by Name


class NameComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.name.compareTo(e2.name);
}
}
// Comparator for sorting by Salary
class SalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return Double.compare(e1.salary, e2.salary);
}
}
public class ComparatorExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(103, "Alice", 50000));
employees.add(new Employee(101, "Bob", 70000));
employees.add(new Employee(102, "Charlie", 60000));

// Sorting by Name
employees.sort(new NameComparator());
System.out.println("Sorted by Name:\n" + employees);

// Sorting by Salary
employees.sort(new SalaryComparator());
System.out.println("\nSorted by Salary:\n" + employees);
}
}
Output
Sorted by Name:
[ID: 103, Name: Alice, Salary: 50000.0, ID: 101, Name: Bob, Salary: 70000.0, ID: 102,
Name: Charlie, Salary: 60000.0]

Sorted by Salary:
[ID: 103, Name: Alice, Salary: 50000.0, ID: 102, Name: Charlie, Salary: 60000.0, ID: 101,
Name: Bob, Salary: 70000.0]

Difference Between Comparable and Comparator:

Feature Comparable Comparator


Package java.lang java.util
Implementation The class implements A separate class implements
Comparable<T> Comparator<T>
Method compareTo(T o) compare(T o1, T o2)
Sorting Basis Defines natural ordering Defines custom ordering
(default)
Number of Fields Only one field at a time Can sort by multiple fields
Modification Needs to modify original class No changes needed in original
class
Example Usage Collections.sort(list) Collections.sort(list, new
ComparatorClass())
1. toString() Method
 Defined in Object class and commonly overridden in custom classes.
 Converts an object into a human-readable string representation.
 Used when printing objects (e.g., System.out.println(obj); implicitly calls
obj.toString()).
 Helps in debugging and logging.

Example: toString() in Collections

import java.util.*;
class Employee {
int id;
String name;
double salary;

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}
// Overriding toString()
@Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
}
public class ToStringExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(101, "Alice", 50000));
employees.add(new Employee(102, "Bob", 60000));
System.out.println(employees); // Calls toString() implicitly
}
}
Output

[ID: 101, Name: Alice, Salary: 50000.0, ID: 102, Name: Bob, Salary: 60000.0]

You might also like