Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Generics and Collections in Java

Basics of Java Generics

Uploaded by

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

Generics and Collections in Java

Basics of Java Generics

Uploaded by

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

SDE Readiness Training

Empowering Tomorrow’s Innovators


Module I
Java Software Development:
Effective Problem Solving

2 Collections in Java | © SmartCliff | Internal | Version 1.0


Generics in Java
Learning Level: Basic

DATE: 30/09/2024
Generics in Java

Generics - Introduction
• When using Java, we often write classes and algorithms that work around certain data types. Let’s
look at the following class as an example:

public class StringBox {


public String myString;
}

• In the example above, we have a StringBox class which represents a real-world box of words.
• This class’s methods perform all of their computations with regards to the String myString field.
What if we wanted a box of ints? We could create a new class:

public class IntegerBox {


public int myInt;

4 Generics in Java | © SmartCliff | Internal | Version 1.0


Generics in Java

Generics - Introduction
• The example above meets our requirements, but as the program grows and we need more types of
boxes, it will become unmanageable. We can solve this problem by using generics.
• Generics, like the name implies, allow us to create generic classes and methods by specifying a type
parameter. We can make StringBox and IntegerBox into a generic Box class like so:

public class Box<T> {


private T data;
}

• In the example above, we created a generic Box class with a type parameter T. All class methods
perform their computation around the T-type parameter We can now specify that we want a String,
Integer, or any other type of Box by specifying a type argument.

5 Generics in Java | © SmartCliff | Internal | Version 1.0


Generics in Java

Generics - Introduction
public class Box <T> {
private T data;
public Box(T data) {
this.data = data;
}
public T getData() {
return this.data;
}
}
• In the example above, notice that:
• The type parameter must be specified within the diamond operator (<>) after the class name.
• The type parameter, T, is similar to a method parameter but instead receives a class or interface
type as an argument as opposed to a reference or primitive type.

6 Generics in Java | © SmartCliff | Internal | Version 1.0


Generics in Java

Generics - Introduction
• The constructor accepts a T-type parameter to initialize data.

• The getter method returns the type parameter T when returning data.

Box<String> myStringBox = new Box<>("Apple")

• In the example above, the object myStringBox is created like a non-generic object, but differs in:

• Needing the diamond operator with the class or interface type argument, <String> in this example,

after the class name.

• Needing the empty diamond operator before calling the constructor new Box<>("Apple").

7 Generics in Java | © SmartCliff | Internal | Version 1.0


Generics in Java

Generics - Introduction
• it’s best practice to make them single, uppercase letters to easily distinguish them from the names of

classes or variables.

• By convention, type parameters are E (Elements), K (Key), N (Number), T (Type), V (Value), and S (or

U or V) for multiple type parameters.

8 Generics in Java | © SmartCliff | Internal | Version 1.0


Generics in Java

Generics - Introduction
// Storage class into a generic class so that it can // Storage an Integer
store values of any type
Storage<Integer> integerStorage = new
public class Storage<T> { Storage<>();
private T value;
integerStorage.setValue(123);
public void setValue(T value) { Integer intValue = integerStorage.getValue();
this.value = value;
} System.out.println("Integer Value: " + intValue);
// Storage an string
public T getValue() {
return value; Storage<String> stringStorage = new
} Storage<>();
}
stringStorage.setValue("Hello");
String strValue = stringStorage.getValue();
System.out.println("String Value: " + strValue);

9 Generics in Java | © SmartCliff | Internal | Version 1.0


Generics in Java

Generics - Introduction
Generics Method

• Like the generic class, we can create a generic method that can accept any type of arguments.

• Here, the scope of arguments is limited to the method where it is declared.

• It allows static as well as non-static methods.

public class TestGenerics3{ public static void main( String args[] ) {


public static < E > void printArray(E Integer[] intArray = { 10, 20, 30, 40, 50 };
[] elements) { Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','
for ( E element : elements){ T' };
System.out.println(element ); System.out.println( "Printing Integer Array" );
} printArray( intArray );
System.out.println(); System.out.println( "Printing Character Array" );
} printArray( charArray );
}
}

10 Generics in Java | © SmartCliff | Internal | Version 1.0


Collections in Java
Learning Level: Basic

DATE:
Collections in Java

Collections - Introduction

• Collections is an object or a container that stores a group of other objects.

• Single unit that contains and manipulates a group of objects.

• Used to standardize the way in which objects are handled in the class.

Real-life use cases

• Linked list - browsing history, trains coaches who are connected to each other, etc.

• Stacks - stack of plates or trays in which the topmost one gets picked first.

• Queue - same as the real-life queues, the one who enters the queue first, leaves it first too.

12 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Collections - Introduction

• The Java Collections Framework - unified architecture for representing and manipulating

collection

• Standardizes the way in which groups of objects are handled by your programs

• Hierarchy of interfaces and classes that provides easy management of a group of objects.

• Java provided ad hoc classes such as Dictionary, Vector, Stack and Properties to store and

manipulate groups of objects

13 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Collections - Introduction

• The Collections Framework was designed to meet several goals.

• First, the framework had to be high-performance. The implementations for the fundamental

collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient.

• Second, the framework had to allow different types of collections to work in a similar manner and with

a high degree of interoperability.

• Third, extending and/or adapting a collection had to be easy.

• Fourth, Facilitates code reusability

14 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Hierarchy of Collection Framework

15 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Iterable Interface

• Root interface for the entire collections framework and Used to iterate over the elements of the

collections.

• Iterator <E> iterator()

Returns an iterator of type E for the collection

16 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interfaces

• The Collection interface is the foundation upon which the Collections Framework is built because

it must be implemented by any class that defines a collection.

• Collection is a generic interface that has this declaration:

interface Collection<E>

Here, E specifies the type of objects that the collection will hold.

• It provides basic operations like adding, removing, clearing the elements in a collection,

checking whether the collection is empty, etc.

• Collection extends the Iterable interface.

17 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interfaces

• The Collections Framework defines several core interfaces

18 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interfaces

• In addition to the collection interfaces, collections also use the Comparator, RandomAccess,

Iterator, ListIterator, and Spliterator interfaces.

• Comparator defines how two objects are compared.

• Iterator, ListIterator and Spliterator enumerate the objects within a collection.

• By implementing RandomAccess, a list indicates that it supports efficient, random access to its

elements.

19 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interfaces

• To provide the greatest flexibility in their use, the collection interfaces allow some methods to be

optional.

• The optional methods enable you to modify the contents of a collection.

• Collections that support these methods are called modifiable.

• Collections that do not allow their contents to be changed are called unmodifiable.

• If an attempt is made to use one of these methods on an unmodifiable collection, an

UnsupportedOperationException is thrown.

20 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interface

• Collection declares the core methods that all collections will have. These methods are

21 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Collection Interface

22 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

• The List interface extends Collection and declares the behavior of a collection that stores a

sequence of elements.

• Elements can be inserted or accessed by their position in the list, using a zero-based index.

• List is used to store ordered collection of data and it may contain duplicates elements.

• List is a generic interface that has this declaration:

interface List<E>

Here, E specifies the type of objects that the list will hold.

• In addition to the methods defined by Collection, List defines some of its own

23 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

24 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

• In addition to the methods defined by Collection, List defines some of its own

25 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Interface

26 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The ArrayList Class

• The ArrayList class extends AbstractList and implements the List interface.

• ArrayList is a generic class that has this declaration:

class ArrayList<E>

Here, E specifies the type of objects that the list will hold.

• ArrayList supports dynamic arrays that can grow as needed (increase or decrease in size)

• In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink,

which means that you must know in advance how many elements an array will hold.

• The Collections Framework defines ArrayList which is a variable-length array of object references.

• ArrayList cannot be used for primitive data types like int, char, etc. , we need to use a wrapper class.

27 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #1

/*This example demonstrate the ArrayList Classes*/


import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
//Create an Arraylist
ArrayList <String> Arr = new ArrayList<String>();
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add("C");
Arr.add("A");
Arr.add("E");
Arr.add("B");
Arr.add("D");
Arr.add("F");
Arr.add(1, "G");
System.out.println("After Insert the Size of Array List is "+Arr.size());
28 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #1

System.out.println("Contents of ArrayList "+Arr);


//Remove Element from array List
Arr.remove("F");
Arr.remove(2); Output:
System.out.println("Contents of ArrayList "+Arr);
Initial Size of Array List is 0
}
After Insert the Size of Array List is 7
}
Contents of ArrayList [C, G, A, E, B,
D, F]
Contents of ArrayList [C, G, E, B, D]

29 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #2

/*This example demonstrate the ArrayList Classes*/


import java.util.*;

public class ArrayListDemo {


public static void main(String args[]) {
//Create an Arraylist
ArrayList <Integer> Arr = new ArrayList<Integer>();
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add(1);
Arr.add(2);
Arr.add(3);
Arr.add(4);
System.out.println("After Insert the Size of Array List is "+Arr.size());
System.out.println("Contents of ArrayList "+Arr);
30 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #2

Integer ia[] = new Integer[Arr.size()];


ia = Arr.toArray(ia);
int sum = 0;
for(int i:ia) { Output:
sum+=i; Initial Size of Array List is 0
} After Insert the Size of Array List is
System.out.println("Sum value is "+sum); 4
} Contents of ArrayList [1, 2, 3, 4]
} Sum value is 10

31 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

/* Create a class called Student with fields for storing a student's name, roll number, and course name.Implement

the following functionalities using an ArrayList:

-Add a new student to the system.

-Remove a student from the system using the roll number.

-Search for a student by roll number and display their details.

-Display all students currently enrolled in the system. */

32 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

import java.util.ArrayList;

import java.util.Scanner;

class Student {

private String name;

private int rollNumber;

private String courseName;

public Student(String name, int rollNumber, String courseName) {

this.name = name;

this.rollNumber = rollNumber;

this.courseName = courseName;

}
33 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #3

public int getRollNumber() {

return rollNumber;

public String toString() {

return "Name: " + name + ", Roll Number: " + rollNumber + ", Course: " + courseName;

34 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

public class StudentManagementSystem {

private ArrayList<Student> students;

public StudentManagementSystem() {

students = new ArrayList<>();

public void addStudent(String name, int rollNumber, String course) {

Student student = new Student(name, rollNumber, course);

students.add(student);

System.out.println("Student added successfully.");

35 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

public void removeStudent(int rollNumber) {

for (Student student : students) {

if (student.getRollNumber() == rollNumber) {

students.remove(student);

System.out.println("Student removed successfully.");

return;

System.out.println("Student with roll number " + rollNumber + " not found.");

36 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

public void searchStudent(int rollNumber) {

for (Student student : students) {

if (student.getRollNumber() == rollNumber) {

System.out.println(student);

return;

System.out.println("Student with roll number " + rollNumber + " not found.");

37 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

public void displayAllStudents() {

if (students.isEmpty()) {

System.out.println("No students enrolled.");

} else {

for (Student student : students) {

System.out.println(student);

38 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

public static void main(String[] args) {

StudentManagementSystem system = new StudentManagementSystem();

Scanner scanner = new Scanner(System.in);

system.addStudent("Alice", 101, "Computer Science");

system.addStudent("Bob", 102, "Mathematics");

system.addStudent("Carol", 103, "Physics");

// Display all students

System.out.println("All students:");

system.displayAllStudents();

39 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #3

// Search for a student

System.out.println("Search for student with Roll Number 102:");

system.searchStudent(102);

// Remove a student

System.out.println("Remove student with Roll Number 101:");

system.removeStudent(101);

// Display all students after removal

System.out.println("All students after removal:");

system.displayAllStudents();

}
40 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Array List Class– Example #4

// Using Array and finding the average of numbers numbers[i] = scanner.nextInt(); // Fill array with
import java.util.Scanner; user input
public class AverageOfNumbersArray { sum += numbers[i]; // Add to sum
public static void main(String[] args) { }
Scanner scanner = new Scanner(System.in); // Calculate average
System.out.print("Enter the number of integers you want to
double average = (double) sum / n;
average: ");
int n = scanner.nextInt(); // Display the average
int[] numbers = new int[n]; // Array to hold integers System.out.println("Average of the entered
int sum = 0;
integers is: " + average);
// Populate the array with integers and calculate the sum
for (int i = 0; i < n; i++) { }
System.out.print("Enter integer " + (i + 1) + ": "); }

41 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #4

// Using ArrayList and finding the average of numbers


import java.util.ArrayList;
import java.util.Scanner;
public class AverageOfNumbersArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of integers you want to average: ");
int n = scanner.nextInt();
ArrayList<Integer> numbers = new ArrayList<>(); // ArrayList to hold integers
int sum = 0;

42 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array List Class– Example #4

// Populate the ArrayList with integers and calculate the sum


for (int i = 0; i < n; i++) {
System.out.print("Enter integer " + (i + 1) + ": ");
int input = scanner.nextInt();
numbers.add(input); // Add user input to the ArrayList
sum += input; // Add to sum
}
// Calculate average
double average = (double) sum / n;
// Display the average
System.out.println("Average of the entered integers is: " + average);
}
}

43 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedList Class

• The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces.

• It provides a linked-list data structure (elements are called as nodes) that is Elements are not
stored in a contiguous memory.

• LinkedList uses Doubly Linked List to store its elements while ArrayList internally uses a dynamic
array to store its elements.

• LinkedList is faster in the manipulation of data as it is node-based

• LinkedList is non-synchronized means multiple threads at a time can access the code

• LinkedList is a generic class that has this declaration:

class LinkedList<E>

Here, E specifies the type of objects that the list will hold.

44 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedList Class

LinkedList has the two constructors shown here:

• LinkedList()

builds an empty linked list

• LinkedList(Collection<? extends E> c)

builds a linked list that is initialized with the elements of the collection c

• LinkedList also implements the Deque interface

45 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked List Class– Example #1

/* Create a program that allows users to add names, remove names, and display the list of
names using a LinkedList*/
import java.util.LinkedList;
import java.util.Scanner;
public class NameManager {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>(); // Create a LinkedList to hold names
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nMenu:");
System.out.println("1. Add Name");
System.out.println("2. Remove Name");
System.out.println("3. Display Names");
System.out.println("4. Exit");
46 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Linked List Class– Example #1

System.out.print("Choose an option: ");


int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1: // Add Name
System.out.print("Enter name to add: ");
String nameToAdd = scanner.nextLine();
names.add(nameToAdd); // Add name to the LinkedList
System.out.println(nameToAdd + " has been added.");
break;

47 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked List Class– Example #1

case 2: // Remove Name


System.out.print("Enter name to remove: ");
String nameToRemove = scanner.nextLine();
if (names.remove(nameToRemove)) {
System.out.println(nameToRemove + " has been removed.");
} else {
System.out.println(nameToRemove + " not found in the list.");
}
break;

48 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked List Class– Example #1

case 3: // Display Names


System.out.println("Names in the list:");
for (String name : names) {
System.out.println(name);
}
break;
case 4: // Exit
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid option. Please try again.");
}
}
}
49 }
Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Linked List Class

Advantages of Using LinkedList:

• Dynamic Size: Unlike arrays, a LinkedList can grow and shrink in size dynamically.

• Efficient Insertions/Deletions: Adding or removing elements is generally more efficient in a

LinkedList than in an array or an ArrayList, especially for large lists, as it does not require

shifting elements.

50 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Vector Class

• Vector uses a dynamic array to store the data elements and it is similar to ArrayList.

• It is synchronized and contains many methods that are not the part of Collection framework.

Methods to create the constructor of Vectors

• Vector<Data-type> v = new Vector<Data-Type>() - default size of Vectors is 10

• Vector<Data-type> v = new Vector<Data-Type>(int size) - specifying the desired size

• Vector<Data-type> v = new Vector<Data-Type>(int size,int incr) - initial capacity is declared by

size, increment specifies number of elements to allocate each time that vector gets resized upward

• Vector<Data-type> v = new Vector<Data-Type>(Collection C) - Creating a Vector from Collection

51 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Vector Class– Example #1

/*This example demonstrate the Vector Class*/


import java.util.*;

public class VectorDemo {


public static void main(String args[]){
Vector<String> v=new Vector<String>();
System.out.println("Size of the vector is "+v.size());
v.add("A");
v.add("B");
v.add("C");
v.add("D");
System.out.println("Elements in the vector "+v);
System.out.println("Size of the vector is "+v.size());
52 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Vector Class– Example #1

v.remove("A");
System.out.println("Elements in the vector after remove "+v);
System.out.println("Size of the vector after the removal is "+v.size());
}
}
Output:
Size of the vector is 0
Elements in the vector [A, B, C, D]
Size of the vector is 4
Elements in the vector after remove [B, C, D]
Size of the vector after the removal is 3

53 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class

• The stack is the subclass of Vector.

• It implements the last-in-first-out data structure, i.e., Stack.

• The stack contains all of the methods of Vector class and also provides its methods like boolean

pop(), boolean peek(), boolean push(object o) which defines its properties.

• Stack is thread-safe

54 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #1

/*This example demonstrate the Stack Class*/


import java.util.*;

public class StackDemo {


public static void main(String args[]){
Stack<String> stk=new Stack<String>();
System.out.println("Size of the stack is "+stk.size());
stk.push("A");
stk.push("B");
stk.push("C");
stk.push("D");
System.out.println("Elements in the stack "+stk);
System.out.println("Size of the stack is "+stk.size());
stk.pop();

55 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #1

System.out.println("Elements in the stack after remove "+stk);


System.out.println("Size of the stack after the removal is "+stk.size());
}
}
Output:
Size of the stack is 0
Elements in the stack [A, B, C, D]
Size of the stack is 4
Elements in the stack after remove [A, B, C]
Size of the stack after the removal is 3

56 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #2


/*This example demonstrate the reverse the string using loop */
public class StringReverser {
public static void main(String[] args) {
String input = "hello"; // Example input
String reversed = reverseString(input);
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + reversed);
}
public static String reverseString(String str) {
String reversed = ""; // Initialize an empty string to hold the reversed string

57 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #2


// Iterate from the end of the string to the beginning
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i); // Append each character to the reversed string
}
return reversed; // Return the reversed string
}
}

58 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #2


/*This example demonstrate the reverse the string using Stack class */
import java.util.Stack;
public class StringReverser {
public static void main(String[] args) {
String input = "hello"; // Example input
String reversed = reverseString(input);
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + reversed);
}
public static String reverseString(String str) {
Stack<Character> stack = new Stack<>(); // Create a stack to hold characters

59 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Stack Class– Example #2


// Push each character of the string onto the stack
for (char ch : str.toCharArray()) {
stack.push(ch);
}
StringBuilder reversed = new StringBuilder(); // StringBuilder to build the reversed string
// Pop characters from the stack and append to the reversed string
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return reversed.toString(); // Return the reversed string
}
}

60 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Scenario to Prefer the List Interface

1. ArrayList

• Scenario: When you need fast access to elements by index and have a relatively stable size or need
occasional resizing.

• Use Case:

– Implementing a dynamic array where you frequently read elements using their index.

– When the application requires iterating over elements, as ArrayList provides good performance in
traversal.

• Advantages:

– Provides O(1) time complexity for accessing elements by index.


– Generally uses less memory compared to LinkedList because it does not store extra references for
nodes.
61 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

Scenario to Prefer the List Interface

• Disadvantages:

– Insertion and deletion operations can be costly (O(n)) if they occur at arbitrary positions since
elements may need to be shifted.

NOTE:

• Because the internal array is stored as a continuous block, access to elements by index is
constant time (O(1)). This is one of the primary advantages of using an ArrayList over other
collections like LinkedList.
• The JVM can quickly compute the memory address of any element in the array using the formula:

• This formula allows for fast, direct access to elements at any index.

62 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Scenario to Prefer the List Interface


LinkedList
 Scenario: When you need frequent insertions and deletions from both ends or within the list.
 Use Case:
o Implementing queues, stacks, or scenarios where you frequently add or remove elements from
the beginning or middle of the list.
o When you need to efficiently manage a dynamic size list with frequent modifications.
 Advantages:
o Provides O(1) time complexity for insertions and deletions at the beginning and end of the list.
o More efficient than ArrayList for scenarios involving numerous insertions and deletions.
 Disadvantages:
o Accessing elements by index is O(n), which is slower than ArrayList.
o More memory overhead due to storing additional pointers (next and previous) for each node.

63 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Scenario to Prefer the List Interface


Vector
 Scenario: When you need a thread-safe list with synchronized access.
 Use Case:
o In multi-threaded environments where you require a collection that can be safely accessed by
multiple threads.
o When you are working with legacy code that relies on Vector.
 Advantages:
o Automatically synchronizes access to elements, making it safe for concurrent use.
 Disadvantages:
o Slower than ArrayList due to synchronization overhead.
o It has a legacy status; generally, ArrayList is preferred unless synchronization is necessary.

64 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Scenario to Prefer the List Interface


Stack
 Scenario: When you need a last-in-first-out (LIFO) data structure.
 Use Case:
o Implementing algorithms that require backtracking, such as depth-first search, or managing
function calls and undo operations.
o When you need to maintain a history of operations or items.
 Advantages:
o Provides methods specifically designed for stack operations (push, pop, peek).
 Disadvantages:
o Stack is a subclass of Vector, so it inherits its synchronization and performance drawbacks.
o If you're looking for a more modern alternative, consider using Deque from the java.util package
for stack operations.

65 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Set Interface

• The Set interface defines a set (unordered collection)

• It extends Collection and specifies the behavior of a collection that does not allow duplicate

elements.

• The add( ) method returns false if an attempt is made to add duplicate elements to a set.

• With two exceptions, it does not specify any additional methods of its own.

• Set is a generic interface that has this declaration:

interface Set<E>

Here, E specifies the type of objects that the set will hold.

66 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Set Interface

67 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class

• HashSet extends AbstractSet and implements the Set interface.

• It creates a collection that uses a hash table for storage which uses a mechanism called Hashing

• HashSet is a generic class that has this declaration:

class HashSet<E>

Here, E specifies the type of objects that the set will hold.

• In hashing, the informational content of a key is used to determine a unique value, called its hash

code.

• The hash code is then used as an index, at which the data associated with the key is stored.

68 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class

• When we insert elements into the HashSet, it is not guaranteed that it gets stored in the same

order and we can store Null values in this

• HashSet is non-synchronized means multiple threads at a time can access the code.

• HashSet does not define any additional methods beyond those provided by its superclasses and

interfaces.

Methods to create the constructors of HashSet

• Creating an empty HashSet - default initial capacity is 16.

HashSet<Data-type> hs = new HashSet<Data-type>()

69 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class

• Creating a HashSet with a specified size

HashSet<Data-type> hs = new HashSet<Data-type>(int size)

• Creating a HashSet with a specified size and fill ratio

HashSet<Data-type> hs = new HashSet<Data-type>(int size,float fillRatio)

• Creating a HashSet from Collection

HashSet<Data-type> hs = new HashSet<Data-type>(Collection C)

70 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #1


/*This example demonstrate the Hashset Class*/
import java.util.*;
public class HashSetDemo {
public static void main(String args[]){
HashSet<String> hs=new HashSet<String>();
System.out.println("Size of the HashSet is "+hs.size());
//adding elements
hs.add("Alpha");
hs.add("Beta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Eta");
hs.add("Omega");
System.out.println("Elements in the HashSet "+hs);
System.out.println("Size of the HashSet is "+hs.size());

71 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #1

hs.remove("Eta");
System.out.println("Elements in the HashSet after remove "+hs);
System.out.println("Size of the HashSet after the removal is "+hs.size());
}
}

Output:
Size of the HashSet is 0
Elements in the HashSet [Gamma, Eta, Alpha, Epsilon, Omega, Beta]
Size of the HashSet is 6
Elements in the HashSet after remove [Gamma, Alpha, Epsilon, Omega, Beta]
Size of the HashSet after the removal is 5

72 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #2


/*This example demonstrate finding the Intersection of two Arrays without collection*/
public class ArrayIntersectionWithoutCollections {
public static void main(String[] args) {
int[] array1 = {1, 3, 4, 5, 7};
int[] array2 = {3, 5, 6, 7, 8};
// Find the intersection of the two arrays
int[] intersection = findIntersection(array1, array2);
// Print the result
System.out.print("Intersection of two arrays: ");
for (int i = 0; i < intersection.length; i++) {
if (intersection[i] != 0) {
System.out.print(intersection[i] + " ");
}
}
}

73 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #2


public static int[] findIntersection(int[] array1, int[] array2) {
// Create an array to store the intersection results with a maximum possible size
int[] result = new int[Math.min(array1.length, array2.length)];
int resultIndex = 0;
// Iterate through the first array
for (int i = 0; i < array1.length; i++) {
// Check if the element exists in the second array
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
// Check if the element is already in the result array to avoid duplicates
boolean alreadyAdded = false;
for (int k = 0; k < resultIndex; k++) {
if (result[k] == array1[i]) {
alreadyAdded = true;
break;

74 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #2


}
}
// If the element is not already in the result, add it
if (!alreadyAdded) {
result[resultIndex++] = array1[i];
}
break; // No need to keep checking once the match is found
}
}
}
// Return the intersection result
return result;
}
}

75 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #2

/*This example demonstrate finding the Intersection of two Arrays with collection*/
import java.util.HashSet;
import java.util.Set;
public class ArrayIntersection {
public static void main(String[] args) {
int[] array1 = {1, 3, 4, 5, 7};
int[] array2 = {3, 5, 6, 7, 8};
Set<Integer> intersection = findIntersection(array1, array2);
System.out.println("Intersection of two arrays: " + intersection);
}
public static Set<Integer> findIntersection(int[] array1, int[] array2) {
HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> resultSet = new HashSet<>();

76 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashSet Class– Example #2

// Add all elements of array1 to set1


for (int num : array1) {
set1.add(num);
}
// Check if elements of array2 are present in set1
for (int num : array2) {
if (set1.contains(num)) {
resultSet.add(num); // Add to resultSet if found
}
}
return resultSet;
}
}

77 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class

• The LinkedHashSet class extends HashSet and adds no members of its own.

• It is a generic class that has this declaration:

class LinkedHashSet<E>

Here, E specifies the type of objects that the set will hold.

• Its constructors parallel those in HashSet.

• LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were

inserted.

• LinkedHashSet is non-synchronized means multiple threads at a time can access the code

78 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #1


/*This example demonstrate the Stack Class*/
import java.util.*;

public class LinkedHashSetDemo01 {


public static void main(String args[]){
LinkedHashSet<String> hs=new LinkedHashSet<String>();
System.out.println("Size of the LinkedHashSet is "+hs.size());
//adding elements
hs.add("Alpha");
hs.add("Beta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Eta");
hs.add("Omega");
System.out.println("Elements in the LinkedHashSet "+hs);

79 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #1


System.out.println("Size of the LinkedHashSet is "+hs.size());
hs.remove("Eta");
System.out.println("Elements in the LinkedHashSet after remove "+hs);
System.out.println("Size of the LinkedHashSet after the removal is "+hs.size());
}
}

Output:
Size of the LinkedHashSet is 0
Elements in the LinkedHashSet [Alpha, Beta ,Gamma, Epsilon, Eta ,Omega]
Size of the LinkedHashSet is 6
Elements in the LinkedHashSet after remove [Alpha, Beta ,Gamma, Epsilon, Omega]
Size of the LinkedHashSet after the removal is 5

80 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #2


/*This example demonstrate the intersection of two arrays using LinkedHashset class
import java.util.LinkedHashSet;
public class ArrayIntersectionWithLinkedHashSet {
public static void main(String[] args) {
int[] array1 = {1, 3, 4, 5, 7};
int[] array2 = {3, 5, 6, 7, 8};
// Find the intersection of the two arrays
int[] intersection = findIntersection(array1, array2);
// Print the result
System.out.print("Intersection of two arrays: ");
for (int i = 0; i < intersection.length; i++) {
if (intersection[i] != 0) {
System.out.print(intersection[i] + " ");
}
}
}
81 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The LinkedHashSet Class– Example #2


public static int[] findIntersection(int[] array1, int[] array2) {
// Use LinkedHashSet to store the intersection results
LinkedHashSet<Integer> intersectionSet = new LinkedHashSet<>();
// Iterate through the first array
for (int value : array1) {
// Check if the element exists in the second array
for (int j : array2) {
if (value == j) {
intersectionSet.add(value); // Automatically handles duplicates
break; // No need to keep checking once the match is found
}
}
}

82 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The LinkedHashSet Class– Example #2


// Convert LinkedHashSet to an array
int[] result = new int[intersectionSet.size()];
int index = 0;
for (Integer num : intersectionSet) {
result[index++] = num;
}

// Return the intersection result


return result;
}
}

83 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Set Interface

• The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.

• SortedSet is a generic interface that has this declaration:

interface SortedSet<E>

Here, E specifies the type of objects that the set will hold.

• The TreeSet class implements this interface

• In addition to those methods provided by Set, the SortedSet interface declares the methods

summarized

84 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Set Interface

• In addition to the methods defined by Collection, Sorted Set defines some of its own

85 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Set Interface

86 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The NavigableSet Interface

• The NavigableSet interface extends SortedSet and declares the behavior of a collection that

supports the retrieval of elements based on the closest match to a given value or values.

• NavigableSet is a generic interface that has this declaration:

interface NavigableSet<E>

Here, E specifies the type of objects that the set will hold.

87 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The NavigableSet Interface

88 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Navigable Set Interface

• Methods that it inherits from SortedSet, NavigableSet adds those summarized

89 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Navigable Set Interface

90 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The TreeSet Class

• TreeSet extends AbstractSet and implements the NavigableSet interface.

• It creates a collection that uses a tree for storage.

• Objects are stored in sorted, ascending order.

• Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing
large amounts of sorted information that must be found quickly.

• TreeSet is a generic class that has this declaration:

class TreeSet<E>

Here, E specifies the type of objects that the set will hold.

• TreeSet is non-synchronized - Multiple operations on TreeSet can be performed at a time.

91 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The TreeSet Class– Example #1

/*This example demonstrate the TreeSet Class*/


import java.util.*;

public class TreeSetDemo {


public static void main(String args[]){
TreeSet<String> Ts=new TreeSet<String>();
System.out.println("Size of the TreeSet is "+Ts.size());
//adding elements
Ts.add("C");
Ts.add("B");
Ts.add("A");
Ts.add("E");
Ts.add("F");
Ts.add("D");
System.out.println("Elements in the TreeSet "+Ts);

92 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The TreeSet Class– Example #1

System.out.println("Size of the TreeSet is "+Ts.size());


Ts.remove("E");
System.out.println("Elements in the TreeSet after remove "+Ts);
System.out.println("Size of the TreeSet after the removal is "+Ts.size());
}
} Output:
Size of the TreeSet is 0
Elements in the TreeSet [A, B, C, D, E, F]
Size of the TreeSet is 6
Elements in the TreeSet after remove [A, B, C, D, F]
Size of the TreeSet after the removal is 5

93 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Queue Interface

• The Queue interface extends Collection and declares the behavior of a queue, which is often a first-

in, first-out list.

• There are types of queues in which the ordering is based upon other criteria. Queue is a generic

interface that has this declaration:

interface Queue<E>

Here, E specifies the type of objects that the queue will hold.

94 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Queue Interface

95 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Queue Interface

• The methods declared by Queue are

96 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class

• PriorityQueue extends AbstractQueue and implements the Queue interface.

• It creates a queue that is prioritized based on the queue’s comparator.

• PriorityQueue is a generic class that has this declaration:

class PriorityQueue<E>

Here, E specifies the type of objects stored in the queue.

• PriorityQueues are dynamic, growing, as necessary.

• It does not allow null values to be stored inside it

97 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #1

/*This example demonstrate the PriorityQueue Class*/


import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
// Create a priority queue
PriorityQueue<String> priorityQueue = new PriorityQueue<>();
// Insert elements into the priority queue
priorityQueue.add("c");
priorityQueue.add("b");
priorityQueue.add("a");
priorityQueue.add("e");
priorityQueue.add("f");

98 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #1

priorityQueue.add("d");
// Display elements of the priority queue
System.out.println("Elements in the priority queue:");
while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll());
} Output:
} Elements in the priority queue:
} a
b
c
d
e
f
99 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Priority Queue Class– Example #2

/*This example demonstrate the PriorityQueue Class with priority*/


import java.util.*;
class Task implements Comparable<Task> {
private String name;
private int priority;
public Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
public String getName() {
return name;
}

100 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #2

public int getPriority() {


return priority;
}

@Override
public int compareTo(Task other) {
// Higher priority tasks should come first
return Integer.compare(other.priority, this.priority);
}
}

101 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #2

public class Main {


public static void main(String[] args) {
// Instantiate a PriorityQueue of Task objects
PriorityQueue<Task> priorityQueue = new PriorityQueue<>();

// Add elements with specified priority


priorityQueue.add(new Task("Task 1", 3));
priorityQueue.add(new Task("Task 2", 1));
priorityQueue.add(new Task("Task 3", 2));

102 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Priority Queue Class– Example #2

// Poll elements from the priority queue


while (!priorityQueue.isEmpty()) {
Task task = priorityQueue.poll();
System.out.println("Executing: " + task.getName() + " (Priority: " + task.getPriority() +
")");
} Output:

} Executing: Task 1 (Priority: 3)

} Executing: Task 3 (Priority: 2)


Executing: Task 2 (Priority: 1)

103 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

• The Deque interface extends Queue and declares the behavior of a double-ended queue.

• Double-ended queues can function as standard, first-in, first-out queues or as last-in, first-out stacks.

• Deque is a generic interface that has this declaration:

interface Deque<E>

Here, E specifies the type of objects that the deque will hold.

104 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

105 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

• In addition to the methods that it inherits from Queue, Deque adds those methods summarized

106 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The DeQue Interface

107 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array DeQue Class

• The ArrayDeque class extends AbstractCollection and implements the Deque interface.

• It adds no methods of its own.

• ArrayDeque creates a dynamic array and has no capacity restrictions.

• ArrayDeque is a generic class that has this declaration:

class ArrayDeque<E>

Here, E specifies the type of objects stored in the collection.

108 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array Deque Class– Example #1

/*This example demonstrate the ArrayDeque Class*/


import java.util.*;

public class ArrayDequeDemo01 {


public static void main(String args[]){
ArrayDeque<String> ad=new ArrayDeque<String>();
System.out.println("Size of the ArrayDeque is "+ad.size());
ad.push("A");
ad.push("B");
ad.push("C");
ad.push("D");
System.out.println("Elements in the ArrayDeque "+ad);
System.out.println("Size of the ArrayDeque is "+ad.size());

109 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Array Deque Class– Example #1

ad.pop();
System.out.println("Elements in the ArrayDeque after remove "+ad);
System.out.println("Size of the ArrayDeque after the removal is "+ad.size());
}
}

Output:
Size of the ArrayDeque is 0
Elements in the ArrayDeque [D, C, B, A]
Size of the ArrayDeque is 4
Elements in the ArrayDeque after remove [C, B, A]
Size of the ArrayDeque after the removal is 3

110 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

• The maps interface in java is a collection that links a key with value pairs.

• Each entry in the map store the data in a key and its corresponding value.

• Map interface contains only unique keys and does not allow any duplicate keys.

• The map interface in Java is a part of the java.util.map interface.

• A key is an object that you use to access the value later, it is associated with a single value.

• A map is used when you need to search, edit, or remove elements based on a key.

• A Map cannot be traversed, therefore you must use the keySet() or entrySet() method to convert it
into a Set.

• There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap as follows:

111 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Hierarchy

112 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Classes that implements Map

Class Description

Although HashMap implements Map, it doesn't


HashMap
maintain any kind of order.

The implementation of Map is LinkedHashMap.


LinkedHashMap It inherits the class HashMap. The insertion
order is maintained.

both the map and the sortedMap interfaces


TreeMap are implemented. In TreeMap, the order is
always maintained in ascending order.

113 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Interface that extend Map

Interface Description

Duplicate keys are not allowed in a map,


Map
although duplicate values are.

In SortedMap, elements can be traversed in


SortedMap
the sorted order of their keys.

114 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Creating Map Objects

• Since Map is an interface, objects of the type map cannot be created.

• To create an object, we always need a class that extends this map. Also, because Generics were
added in Java 1.5, it is now possible to restrict the types of objects that can be stored in the Map.

Syntax:
// Defining Type-safe Map
Map hm = new HashMap();

Example:
Map<String, String> hm = new HashMap<>();

hm.put("India", "New Delhi");


hm.put("USA", "Washington");
hm.put("United Kingdom", "London");

115 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Characteristics of a Map Interface

• Each key can map to a maximum of one value, and a map cannot contain multiple keys. While
some implementations, like the HashMap and LinkedHashMap, allow null keys and null values,
others, like the TreeMap, do not.

• In the map interface in java, the order depends on the specific implementations. For eg,
TreeMap and LinkedHashMap have a predictable order, whereas HashMap does not.

• Java provides two interfaces for implementing Map. They consist of three classes: HashMap,
LinkedHashMap, and TreeMap as well as Map and a SortedMap.

• Set of keys, Set of Key-Value Mappings, and Collection of Values are the three collection views a
map interface provides.

• Since the Map interface is not a subtype of the Collection interface. Thus, it differs from the other
collection types in terms of features and behaviors.

116 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

When to use the Map interface in Java

• When someone has to retrieve and update elements based on keys or execute lookups by keys,

the maps are used. Additionally, For key-value association mapping like dictionaries, maps are

useful. The following are a few common scenarios:

1.A map of cities and their zip codes.

2.A map of error codes with their descriptions.

3.A map of school classes and the students names. Each key (class) is associated with a list of values

(student).

4.A map of managers and employees in a company.

117 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

• The methods declared by Map are summarized

118 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

119 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Map Interface

120 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The HashMap Class

• The HashMap class extends AbstractMap and implements the Map interface.

• It uses a hash table to store the map.

• This allows the execution time of get( ) and put( ) to remain constant even for large sets.

• HashMap is a generic class that has this declaration:

class HashMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values

121 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class – Example #1

/*This example demonstrate the HashMap Class*/


import java.util.*;

public class HashMapDemo {


public static void main(String args[]){
HashMap<String, Double> tm = new HashMap<String, Double>();
System.out.println("Size of the HashMap is "+tm.size());
tm.put("John Doe", 4343.43);
tm.put("Tom Smith",145.23);
tm.put("Jane Baker", 1450.78);
tm.put("Ralph Smith",-18.76);
System.out.println("Elements in the HashMap "+tm);
System.out.println("Size of the HashMap is "+tm.size());
Set<Map.Entry<String, Double>> set = tm.entrySet();

122 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class– Example #1

for(Map.Entry<String, Double> me:set) {


System.out.print(me.getKey()+":");
Output:
System.out.println(me.getValue());
Size of the HashMap is 0
}
Elements in the HashMap {John
}
Doe=4343.43, Ralph Smith=-18.76, Tom
}
Smith=145.23, Jane Baker=1450.78}
Size of the HashMap is 4
John Doe:4343.43
Ralph Smith:-18.76
Tom Smith:145.23
Jane Baker:1450.78

123 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked HashMap Class

• LinkedHashMap extends HashMap.

• It maintains a linked list of the entries in the map, in the order in which they were inserted.

• When iterating through a collection-view of a LinkedHashMap, the elements will be returned in the
order in which they were inserted.

• You can also create a LinkedHashMap that returns its elements in the order in which they were last
accessed.

• LinkedHashMap is a generic class that has this declaration:

class LinkedHashMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

124 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Linked Hash Map Class – Example #1

/*This example demonstrate the LinkedHashMap Class*/


import java.util.*;

public class LinkedHashMapDemo {


public static void main(String args[]){
LinkedHashMap<String, Double> lhm = new LinkedHashMap<String, Double>();
System.out.println("Size of the LinkedHashMap is "+lhm.size());
lhm.put("John Doe", 4343.43);
lhm.put("Tom Smith",145.23);
lhm.put("Jane Baker", 1450.78);
lhm.put("Ralph Smith",-18.76);
System.out.println("Elements in the LinkedHashMap "+lhm);
System.out.println("Size of the LinkedHashMap is "+lhm.size());
Set<Map.Entry<String, Double>> set = lhm.entrySet();

125 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class– Example #1

for(Map.Entry<String, Double> me:set) {


System.out.print(me.getKey()+":");
Output:
System.out.println(me.getValue());
Size of the LinkedHashMap is 0
}
Elements in the LinkedHashMap {John
}
Doe=4343.43, Tom Smith=145.23, Jane
}
Baker=1450.78, Ralph Smith=-18.76}
Size of the LinkedHashMap is 4
John Doe:4343.43
Tom Smith:145.23
Jane Baker:1450.78
Ralph Smith:-18.76

126 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Map Interface

• The SortedMap interface extends Map.

• It ensures that the entries are maintained in ascending order based on the keys.

• SortedMap is generic and is declared as shown here:

interface SortedMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

127 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Sorted Map Interface

• The methods declared by Sorted Map are summarized

128 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Tree Map Class

• The TreeMap class extends AbstractMap and implements the NavigableMap interface.

• It creates maps stored in a tree structure.

• A TreeMap provides an efficient means of storing key/value pairs in sorted order and allows rapid

retrieval.

• Unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.

• TreeMap is a generic class that has this declaration:

class TreeMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

129 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Tree Map Class – Example #1

/*This example demonstrate the TreeMap Class*/


import java.util.*;

public class TreeMapDemo {


public static void main(String args[]){
TreeMap<String, Double> tm = new TreeMap<String, Double>();
System.out.println("Size of the TreeMap is "+tm.size());
tm.put("John Doe", 4343.43);
tm.put("Tom Smith",145.23);
tm.put("Jane Baker", 1450.78);
tm.put("Ralph Smith",-18.76);
System.out.println("Elements in the TreeMap "+tm);
System.out.println("Size of the TreeMap is "+tm.size());
Set<Map.Entry<String, Double>> set = tm.entrySet();

130 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Hash Map Class– Example #1

for(Map.Entry<String, Double> me:set) {


System.out.print(me.getKey()+":");
Output:
System.out.println(me.getValue());
Size of the LinkedHashMap is 0
}
Elements in the LinkedHashMap {John
}
Doe=4343.43, Tom Smith=145.23, Jane
}
Baker=1450.78, Ralph Smith=-18.76}
Size of the LinkedHashMap is 4
John Doe:4343.43
Tom Smith:145.23
Jane Baker:1450.78
Ralph Smith:-18.76

131 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator

• Iterator is an object that implements either the Iterator or the ListIterator interface.

• Iterator enables you to cycle through a collection, obtaining or removing elements.

• ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

• Iterator and ListIterator are generic interfaces which are declared as shown here:

interface Iterator <E>

interface ListIterator <E>

Here, E specifies the type of objects being iterated.

132 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Iterator Interface

• The methods declared by Iterator are summarized

133 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The List Iterator Interface

• The methods declared by List Iterator are summarized

134 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Example #1

/*This example demonstrate the Collections using Iterator*/


import java.util.*;

public class IteratorDemo01 {


public static void main(String args[]) {
ArrayList <String> Arr = new ArrayList<String>(); //Create an Arraylist
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add("C");
Arr.add("A");
Arr.add("E");
Arr.add("B");
Arr.add("D");
Arr.add("F");
Arr.add(1, "G");
System.out.println("After Insert the Size of Array List is "+Arr.size());

135 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Example #1

System.out.println("Contents of ArrayList using Iterator");


Iterator<String> itr = Arr.iterator(); //Iterator
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element+" ");
}
System.out.println();
ListIterator<String> litr = Arr.listIterator(); //ListIterator
while(litr.hasNext()) {
String element = litr.next();
litr.set(element+"+");
}
System.out.println("Modified Contents of ArrayList using Iterator");
itr = Arr.iterator(); //Iterator

136 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Example #1

while(itr.hasNext()) {
String element = itr.next();
System.out.print(element+" ");
}
System.out.println();
System.out.println("Modified Contents of ArrayList in Backward using ListIterator");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element+" ");
}
}
}

137 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Accessing Collections using Iterator – Output

Output:
Initial Size of Array List is 0
After Insert the Size of Array List is 7
Contents of ArrayList using Iterator
CGAEBDF
Modified Contents of ArrayList using Iterator
C+ G+ A+ E+ B+ D+ F+
Modified Contents of ArrayList in Backward using ListIterator
F+ D+ B+ E+ A+ G+ C+

138 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Spliterators

• JDK 8 added another type of iterator called a spliterator that is defined by the Spliterator interface.

• A spliterator cycles through a sequence of elements and it is similar to the iterators. However, the

techniques required to use it differ.

• It offers substantially more functionality than does either Iterator or ListIterator.

• It provide support for parallel iteration of portions of the sequence. Thus, Spliterator supports parallel

programming.

• It offers a streamlined approach that combines the hasNext and next operations into one method.

139 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Spliterator Interface

• Spliterator is a generic interface that is declared like this:

interface Spliterator<T>

• Here, T is the type of elements being iterated.

• The methods declared by Spliterator are summarized


Method Description
int characteristics() Returns a set of characteristics of this Spliterator and
its elements.
long estimateSize() Returns an estimate of the number of elements that
would be encountered by
a forEachRemaining(java.util.function.Consumer<?
super T>) traversal, or returns Long.MAX_VALUE if
infinite, unknown, or too expensive to compute.
default void forEachRemaining (Consumer<? Performs the given action for each remaining
super T> action) element, sequentially in the current thread, until all
elements have been processed or the action throws an
exception.
140 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Spliterator Interface

• The methods declared by Spliterator are summarized

Method Description
default Comparator<? super T> If this Spliterator's source is SORTED by a Comparator, returns
getComparator() that Comparator.
default long Convenience method that returns estimateSize() if this Spliterator
getExactSizeIfKnown() is SIZED, else -1.
default boolean Returns true if this Spliterator's characteristics() contain all of the
hasCharacteristics given characteristics.
(int characteristics)
boolean tryAdvance If a remaining element exists, performs the given action on it,
(Consumer<? super T> action) returning true; else returns false.
Spliterator<T> trySplit() If this spliterator can be partitioned, returns a Spliterator covering
elements, that will, upon return from this method, not be covered by
this Spliterator.

141 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Spliterator Class – Example #1

/*This example demonstrate the Spliterator*/


import java.util.*;

public class SpliteratorDemo01 {


public static void main(String args[]) {
//Create an Arraylist
ArrayList <Double> Arr = new ArrayList<Double>();
System.out.println("Initial Size of Array List is "+Arr.size());
Arr.add(1.0);
Arr.add(2.0);
Arr.add(3.0);
Arr.add(4.0);
Arr.add(5.0);
Arr.add(6.0);

142 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

The Spliterator Class – Example #1

//Use tryAdvance to print elements


System.out.println("Contents of ArrayList using tryAdvance ");
Spliterator<Double> sitr = Arr.spliterator();
while(sitr.tryAdvance((n)->System.out.print(n+" ")));
System.out.println();
//Use forEachRemaining to print elements
System.out.println("Contents of ArrayList using forEachRemaining ");
sitr = Arr.spliterator();
sitr.forEachRemaining((n)->System.out.print(n+" "));
System.out.println();
System.out.println("Size of Array List after insertion is "+Arr.size());
}
}
143 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

The Spliterator Class – Output

Output:
Initial Size of Array List is 0
Contents of ArrayList using tryAdvance
1.0 2.0 3.0 4.0 5.0 6.0
Contents of ArrayList using forEachRemaining
1.0 2.0 3.0 4.0 5.0 6.0
Size of Array List after insertion is 6

144 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparable

• Java Comparable interface is used to order the objects of the user-defined class.

• This interface is found in java.lang package and contains only one method named compareTo(Object).

• It provides a single sorting sequence only, i.e., we can sort the elements on the basis of single data
member only. For example, Sort based on student regno or name or any other member.

Syntax:
public int compareTo(Object obj)

• It is used to compare the current object with the specified object. It returns :

• Positive integer, if the current object is greater than the specified object.

• Negative integer, if the current object is less than the specified object.

• Zero, if the current object is equal to the specified object.


145 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

Comparable
/***This Example demonstrate sorting using Comparable*/
•import
sdf java.io.*;
import java.util.*;
// A class 'Mobile' that implements Comparable
class Mobile implements Comparable<Mobile>{
private String name;
private int ram;
private int price;
Mobile(String name, int ram, int price){
this.name = name;
this.ram = ram;
this.price = price;
}
String getName() {
return name;
}
int getRam() {
return ram;
}

146 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparable
void setRam(int ram) {
• sdf this.ram = ram;
}
void setName(String name) {
this.name = name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
//compare the current object with the specified object.
public int compareTo(Mobile o) {
if (this.ram > o.getRam())
return 1;
else
return -1;
}
}

147 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparable
//Main Class
•class
sdf ComparableExample {
public static void main(String[] args) {
List<Mobile> mobileList = new ArrayList<>();
mobileList.add(new Mobile("RedMe", 16, 800));
mobileList.add(new Mobile("Apple", 8, 100));
mobileList.add(new Mobile("Samsung", 4, 600));
Collections.sort(mobileList);
System.out.println("Mobiles after sorting : ");
System.out.println("Name"+"\t"+"Ram"+"\t"+"Price");
for (Mobile mb : mobileList) {
System.out.println(mb.getName() + "\t" +
mb.getRam() + "\t" + mb.getPrice());
}
}
}
148 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

Comparator

• Java Comparator interface is used to order the objects of a user-defined class.

• This interface is found in java.util package and contains the following method:

• compare(Object obj1,Object obj2) - It compares the first object with the second object.

• It provides multiple sorting sequences, i.e., we can sort the elements on the basis of any data member,

for example, rollno, name, age or anything else.

149 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparator
/***This Example demonstrate sorting using Comparable and Comparator*/
• sdf
import java.io.*;
import java.util.*;
// A class 'Mobile' that implements Comparable
class Mobile implements Comparable<Mobile>{
private String name;
private int ram;
private int price;
Mobile(String name, int ram, int price){
this.name = name;
this.ram = ram;
this.price = price;
}

150 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparator
String getName() {
• sdf return name;
}
int getRam() {
return ram;
}
int getPrice() {
return price;
}
//compare Mobiles by Ram size
public int compareTo(Mobile o) {
if (this.ram > o.getRam())
return 1;
else
return -1;

151 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparator
// Class to compare Mobiles by price
• sdf
class PriceCompare implements Comparator<Mobile>{
public int compare(Mobile m1, Mobile m2){
if (m1.getPrice() < m2.getPrice()) return -1;
if (m1.getPrice() > m2.getPrice()) return 1;
else return 0;
}
}
// Class to compare Mobiles by name
class NameCompare implements Comparator<Mobile> {
public int compare(Mobile m1, Mobile m2) {
return m1.getName().compareTo(m2.getName());
}
}

152 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparator
// Main class
• sdf
class ComparatorExample{
public static void main(String[] args){
List<Mobile> mobileList = new ArrayList<>();
mobileList.add(new Mobile("RedMe", 16, 800));
mobileList.add(new Mobile("Apple", 8, 100));
mobileList.add(new Mobile("Samsung", 4, 600));
System.out.println("Sorted by Price");
PriceCompare priceCompare = new PriceCompare();
Collections.sort(mobileList, priceCompare);
System.out.println("Mobiles after price sorting : ");
System.out.println("Name"+"\t"+"Ram"+"\t"+"Price");
for (Mobile mb : mobileList){
System.out.println(mb.getName() + "\t" +
mb.getRam() + "\t" +
mb.getPrice());
}
153 Collections in Java | © SmartCliff | Internal | Version 1.0
Collections in Java

Comparator
System.out.println("\nSorted by Name");
• sdf
NameCompare nameCompare = new NameCompare();
Collections.sort(mobileList, nameCompare);
System.out.println("Mobiles after price sorting : ");
System.out.println("Name"+"\t"+"Ram"+"\t"+"Price");
for (Mobile mb : mobileList){
System.out.println(mb.getName() + "\t" +
mb.getRam() + "\t" +
mb.getPrice());
}

154 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparator
// Uses Comparable to sort by Ram
• sdf
System.out.println("\nSorted by Ram Size");
Collections.sort(mobileList);
System.out.println("Name"+"\t"+"Ram"+"\t"+"Price");
for (Mobile mb : mobileList){
System.out.println(mb.getName() + "\t" +
mb.getRam() + "\t" +
mb.getPrice());
}
}
}

155 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Comparable Vs Comparator

S.No Comparable Comparator


1. The comparable interface has a method The comparator interface has a method
compareTo(Object a ) compare(Object O1, Object O2)
2. Comparable interface belongs to java.lang Comparator interface belongs to java.util package.
package.
3. Collection.sort(List) method can be used Collection.sort(List, Comparator) method can be
to sort the collection of Comparable type used to sort the collection of Comparator type
objects. objects.
4. Comparable provides single sorting The comparator provides a multiple sorting
sequence. sequence.

156 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

1. What is Collection in Java?

a) A group of Classes b) A group of Objects

c) A group of Interfaces d) None of the above

b) A group of Objects

157 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

2. Which of the following is not in the Collections in Java ?

a) Array b) Vector

c) Stack d) HashSet

a) Array

158 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

3. Which of the following is the interface?

a) ArrayList b) HashSet

c) Queue d) TreeMap

c) Queue

159 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

4. The Dictionary class provides the capability to store

a) key b) key-value pair

c) value d) None of these

b) key-value pair

160 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

5. Which of the following classes are used to avoid duplicates?

a) ArrayList b) HashSet

c) LinkedList d) LinkedHashSet

b) HashSet & d) LinkedHashSet

161 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

6. In which of the following package, are all of the collection

classes present?

a) java.net b) java.lang

c) java.awt d) java.util

d) java.util

162 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

7. Which of the following interface is not a part of Java’s

collection framework ?

a) SortedList b) Set

c) List d) SortedMap

a) SortedList

163 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

8. Which of these interface handle sequences?

a) Set b) Comparator

c) Collection d) List

d) List

164 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz

9. Which of these methods deletes all the elements from

invoking collection ?

a) clear () b) reset ()

c) delete () d) refresh ()

a) clear ()

165 Collections in Java | © SmartCliff | Internal | Version 1.0


Collections in Java

Quiz
10. What is the output of the following code
import java.util.*;
public class Test {
public static void main(String args[]) {
ArrayList <Integer> al = new ArrayList<Integer>();
for (int i = 5; i > 0; i--)
al.add(i);
for(Integer ele:al) {
System.out.print(ele+" ");
}
}
}

a) 12345 b) 54321

c) 13579 d) 02468

166 Collections in Java | © SmartCliff | Internal | Version 1.0 b) 54321


Success doesn’t
come to you, you
have to go to it.
- Marva Collins

167 Collections in Java | © SmartCliff | Internal | Version 1.0


THANK YOU

You might also like