[go: up one dir, main page]

0% found this document useful (0 votes)
15 views35 pages

Oops Report

Uploaded by

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

Oops Report

Uploaded by

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

REPORT

Collection Frameworks,Generics And


Lambda Expressions

AIM:
To study about different collection frameworks available in java.
1.Linked List:
A linked list is a linear data structure in which elements, known as
nodes, are interconnected using pointers. Each node typically
comprises two components:
1. Data: The actual value or information stored in the node.
2. Reference (or Pointer): A link to the next node in the sequence.
Key Characteristics
• Dynamic Size: Unlike arrays, the size of a linked list can grow or
shrink dynamically, making it suitable for situations where the
number of elements is unpredictable.
• Efficient Insertion/Deletion: Adding or removing elements is
faster compared to arrays, as it does not necessitate shifting
elements.
Types of Linked Lists
1. Singly Linked List: Each node points to the next node, and the
last node points to null.
2. Doubly Linked List: Each node contains two pointers, one to the
previous node and one to the next node.
3. Circular Linked List: The last node links back to the first node,
forming a circular structure.
Advantages
• Efficient Insertion and Deletion: Particularly useful for dynamic
datasets where elements are frequently added or removed.
• Memory Efficient for Variable Sizes: Saves memory when the
dataset size is variable, as it doesn't require pre-allocation.
Disadvantages
• No Random Access: You must traverse the list sequentially from
the head to reach a specific node, which can be time-
consuming.
• Higher Memory Overhead: Requires additional memory for
storing pointers.
Operations on Linked List:
Importing LinkedList:
Import java.util.LinkedList;
With Generics:
LinkedList<String> books = new LinkedList<>();
Without Generics:
LinkedList books = new LinkedList();
Adding Elements
books.add("Moby Dick"); books.add("1984");
Accessing Elements:
System.out.println(books.get(0));
• This gets the book stored at index 0.
Modifying Elements:
books.set(0, "Brave New World");
Removing Elements:
• By index: books.remove(0);
• By element: books.remove("Moby Dick");

Iterating Through the LinkedList:


Without Lambda Expression:
for (int i = 0; i < books.size(); i++) {
System.out.println(books.get(i));
}
Using Lambda Expression:
books.forEach(book -> System.out.println(book));
Checking for an Element:
if (books.contains("Brave New World")) {
System.out.println("Brave New World is in the list.");
}
Clearing the LinkedList:
books.clear(); System.out.println("List after clearing: " + books); //
Output: []
Checking the Size of the LinkedList:
System.out.println("Size of the LinkedList: " + books.size());
Implementation of a Linked List with Generics and
Lambda Expressions:

import java.util.LinkedList;

public class Main {


public static void main(String[] args) {

LinkedList<String> books = new LinkedList<>();


books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");
System.out.println("First book: " + books.get(0)); // Access by
index

books.set(1, "Brave New World");


// Replacing 1984 with Brave New World
System.out.println("After modification: " + books);

// Iterating (Using Lambda Expression)


System.out.println("Books in the list:");
books.forEach(book -> System.out.println(book));

// Checking if an element exists


System.out.println("List contains 'To Kill a Mockingbird': " +
books.contains("To Kill a Mockingbird"));

// Clearing the list


books.clear();
System.out.println("After clearing, size of the list: " +
books.size());
}
}
OUTPUT:
Implementation of a Linked List without Generics:
import java.util.LinkedList;

public class LinkedListWithoutGenerics {


public static void main(String[] args) {
LinkedList books = new LinkedList();
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");
System.out.println("First book: " + books.get(0));
books.set(1, 1999);
System.out.println("After modification: " + books);
System.out.println("Books in the list:");
for (Object book : books) {
System.out.println(book);
}
System.out.println("List contains 'To Kill a Mockingbird': " +
books.contains("To Kill a Mockingbird"));
books.clear();
System.out.println("After clearing, size of the list: " +
books.size());
}
}
OUTPUT:
2.HashMap :
A HashMap in Java is part of the java.util package and is designed to
store data in key-value pairs. It offers an efficient mechanism for
retrieving, updating, and deleting elements based on their keys.
Key Features
1. Key-Value Storage: Each entry in a HashMap is stored as a key-
value pair.
2. Hashing: Utilizes a hash table where the key's hash code
determines its storage location, ensuring fast data access.
3. Unique Keys: Keys must be unique within the HashMap, while
values can be duplicated.
4. Null Values: Supports one null key and multiple null values.
How It Works
• Storing Elements: When a key-value pair is added, the key's
hash code is computed and mapped to a specific bucket in the
hash table.
• Hash Collisions: In case of hash collisions (two keys having the
same hash code), a linked list or tree structure is used within
the bucket to manage the entries.
Performance Characteristics
• Insertion, Deletion, Retrieval: Average time complexity is O(1)
due to efficient hashing.
• Iteration: Time complexity is O(n), as all entries need to be
traversed.
Common Use Cases
• Data Association: Mapping student IDs to names or product
codes to prices.
• Caching: Ensuring fast data retrieval.
• Counting Occurrences: Tracking word frequencies in text.

Operations on HashMap:
Importing HashMap:
import java.util.HashMap;
With Generics:
HashMap<String, String> groceries = new HashMap<>();
Without Generics:
HashMap groceries = new HashMap();
Adding Elements:
groceries.put("Apple", "Fruit");
Accessing Elements:
System.out.println("Value for apple: " + groceries.get("Apple"));
Modifying Elements:
groceries.put("Apple", "Red Fruit");
Removing Elements: :
groceries.remove("Apple");
Without Lambda Expression
for (String key : groceries.keySet()) {
System.out.println(key + ": " + groceries.get(key));
}
With Lambda Expression
groceries.forEach((item, quantity) -> System.out.println(item + " -> "
+ quantity));
Checking if a Key Exists:
if (groceries.containsKey("Banana")) {
System.out.println("Banana exists in the HashMap.");
}
Clearing the HashMap:
groceries.clear();
System.out.println("After clearing the HashMap: " + groceries); //
Output: {}
Checking the Size of the HashMap:
System.out.println("Size of the HashMap: " + groceries.size());
Implementation of a Hashmap with Generics and
Lambda Expressions:

import java.util.HashMap;

public class HashMapWithGenerics {


public static void main(String[] args) {
// Creation
HashMap<String, Integer> books = new HashMap<>();

// Adding Elements (key-value pairs)


books.put("Moby Dick", 5);
books.put("1984", 10);
books.put("To Kill a Mockingbird", 15);

// Accessing Elements
System.out.println("Quantity of 1984: " + books.get("1984"));

// Modifying Elements
books.put("1984", 12); // Update quantity
System.out.println("Updated books: " + books);

// Iterating (Using Lambda Expression)


System.out.println("Books list:");
books.forEach((title, quantity) -> System.out.println(title + " -> "
+ quantity));

// Checking if an element exists


System.out.println("List contains 'To Kill a Mockingbird': " +
books.containsKey("To Kill a Mockingbird"));

// Clearing the HashMap


books.clear();
System.out.println("After clearing, size of the books: " +
books.size());
}
}
OUTPUT:
Implementation of a Hashmap without Generics:
import java.util.HashMap;

public class HashMapWithoutGenerics {


public static void main(String[] args) {
// Creation
HashMap books = new HashMap();

// Adding Elements (key-value pairs)


books.put("Moby Dick", 5);
books.put("1984", 10);
books.put("To Kill a Mockingbird", 15);

// Accessing Elements
System.out.println("Quantity of 1984: " + books.get("1984"));

// Modifying Elements
books.put("1984", 12); // Update quantity
System.out.println("Updated books: " + books);

// Iterating (Using traditional for-each loop)


System.out.println("Books list:");
for (Object title : books.keySet()) {
System.out.println(title + " -> " + books.get(title));
}

// Checking if an element exists


System.out.println("List contains 'To Kill a Mockingbird': " +
books.containsKey("To Kill a Mockingbird"));

// Clearing the HashMap


books.clear();
System.out.println("After clearing, size of the books: " +
books.size());
}
}
OUTPUT:
3.HashSet:
A HashSet in Java is a collection designed to store unique elements
using a hash table. It is part of the java.util package and implements
the Set interface, ensuring no duplicates and no guaranteed order.
Key Features
1. No Duplicates: HashSet does not allow duplicate elements. Any
attempt to add a duplicate will be ignored.
2. No Order Guarantee: Elements are stored based on their hash
codes, so the insertion order is not preserved.
3. Allows Null: A HashSet can contain one null value.
4. Fast Performance: Operations like add, remove, contains, and
size have an average time complexity of O(1).
Internal Mechanics
• Hash Table: HashSet uses a hash table internally, backed by a
HashMap.
• Hash Code: When an element is added, Java computes its hash
code to determine its storage bucket.
• Collision Handling: If two elements have the same hash code
(collision), they are stored in the same bucket using a linked list
or tree structure.
Use Cases
• Removing Duplicates: Ideal for storing unique items like
usernames or IDs.
• Fast Lookup: Efficient for checking if an element exists in the
collection.
• Set Operations: Useful for performing set operations like union,
intersection, and difference.
Operations on HashSet:
Importing HashSet:
import java.util package.
With Generics:
HashSet<String> books = new HashSet<>();
Without Generics:
HashSet books = new HashSet();
Adding Elements:
books.add("Moby Dick");
Removing Elements:
books.remove("1984");
Iterating without Lambda Expression:
for (String book : books) {
System.out.println(book); // Output: Moby Dick, Brave New World
}
Iterating with Lambda Expression:
books.forEach(book -> System.out.println(book));
Checking for an Element without Lambda Expression:
if (books.contains("Moby Dick")) {
System.out.println("Moby Dick is in the list.");
}
Checking for an Element with Lambda Expression:
books.stream().filter(book -> book.equals("Moby
Dick")).forEach(book -> System.out.println("Moby Dick is in the
list."));
Clearing the HashSet:
books.clear(); System.out.println("After clearing: " + books); //
Output: []
Checking the Size of the HashSet:
System.out.println("Size of the HashSet: " + books.size());
import java.util.HashSet;
Implementation of Hashset with Generics and Lambda
Expressions:
public class HashSetWithGenerics {
public static void main(String[] args) {
// Creation
HashSet<String> books = new HashSet<>();

// Adding Elements
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");

// Accessing Elements
System.out.println("Books in the collection:");
books.forEach(book -> System.out.println(book)); // Using
Lambda Expression

// Checking if an element exists


if (books.contains("1984")) {
System.out.println("1984 is in the collection.");
}

// Removing an Element
books.remove("1984");
System.out.println("After removing 1984, books in the
collection: " + books);

// Checking the Size of the HashSet


System.out.println("Size of the collection: " + books.size());

// Clearing the HashSet


books.clear();
System.out.println("After clearing, size of the collection: " +
books.size()); // Output: 0
}
}
OUTPUT:
Implementation of Hashset without Generics :
public class HashSetWithGenerics {
public static void main(String[] args) {
// Creation
HashSet books = new HashSet();

// Adding Elements
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");

// Accessing Elements
System.out.println("Books in the collection:");
books.forEach(book -> System.out.println(book)); // Using
Lambda Expression

// Checking if an element exists


if (books.contains("1984")) {
System.out.println("1984 is in the collection.");
}

// Removing an Element
books.remove("1984");
System.out.println("After removing 1984, books in the
collection: " + books);

// Checking the Size of the HashSet


System.out.println("Size of the collection: " + books.size());

// Clearing the HashSet


books.clear();
System.out.println("After clearing, size of the collection: " +
books.size()); // Output: 0
}
}
OUTPUT:
4.TreeSet
A TreeSet in Java is a collection that stores unique elements in a
sorted manner. It is part of the java.util package and implements the
Set interface while maintaining elements in ascending order by
default. Internally, it uses a Red-Black Tree data structure, ensuring
efficient operations with a time complexity of O(log n) for insertion,
deletion, and lookup.
Key Features of TreeSet
1. Sorted Order: Elements are automatically sorted in their
natural ascending order, or according to a custom comparator if
provided.
2. No Duplicates: A TreeSet does not allow duplicate elements.
Any attempt to add a duplicate will be ignored.
3. Automatic Sorting: Elements are automatically sorted upon
insertion, eliminating the need for manual sorting.
4. NavigableSet Interface: Provides advanced navigation methods
like first(), last(), ceiling(), and floor().
How TreeSet Works
• Balanced Binary Search Tree: Utilizes a Red-Black Tree, a
balanced binary search tree, for internal storage.
• Insertion: Elements are placed in their correct position based
on the sorting order upon insertion.
• Handling Duplicates: Duplicate elements are silently ignored,
ensuring that all elements remain unique.
Common Use Cases
• Sorted Data Storage: Ideal for scenarios where elements need
to be stored in a sorted order.
• Range Queries: Efficient for finding elements within specific
ranges.
• Unique and Ordered Data: Useful for maintaining a collection
with automatic ordering and uniqueness.

Operations on TreeSet :

Importing TreeSet:

import java.util.TreeSet;

With Generics:

TreeSet<String> books = new TreeSet<>();

Without Generics:

TreeSet books = new TreeSet();

Adding Elements:

books.add("Moby Dick");

Accessing Elements:

System.out.println("First Element: " + books.first()); // First


element

Removing Elements:

books.remove("1984"); // Removes element "1984"


Iterating without Lambda Expression:

for (Object book : books) {


System.out.println(book);
}

Iterating with Lambda Expression

books.forEach(book -> System.out.println(book));

Checking for an Element:

System.out.println("Contains 'To Kill a Mockingbird': " +


books.contains("To Kill a Mockingbird"));

Clearing the TreeSet:

books.clear();
System.out.println("After clearing, size of the TreeSet: " +
books.size());
Implementation of Treeset with Generics and Lambda
Expressions:
import java.util.TreeSet;

public class TreeSetWithGenerics {


public static void main(String[] args) {
// Creation
TreeSet<String> books = new TreeSet<>();

// Adding Elements
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");

// Accessing Elements
System.out.println("First Book: " + books.first());

// Iterating (Using Lambda Expression)


System.out.println("Books in the collection:");
books.forEach(book -> System.out.println(book));

// Checking if an element exists


if (books.contains("1984")) {
System.out.println("1984 is in the collection.");
}

// Removing an Element
books.remove("1984");
System.out.println("After removing 1984, books in the
collection: " + books);

// Checking the Size of the TreeSet


System.out.println("Size of the collection: " + books.size());

// Clearing the TreeSet


books.clear();
System.out.println("After clearing, size of the collection: " +
books.size()); // Output: 0
}
}
OUTPUT:
Implementation of Treeset without Generics:
import java.util.TreeSet;

public class TreeSetWithGenerics {


public static void main(String[] args) {
// Creation
TreeSet books = new TreeSet();

// Adding Elements
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");

// Accessing Elements
System.out.println("First Book: " + books.first());

// Iterating (Using Lambda Expression)


System.out.println("Books in the collection:");
books.forEach(book -> System.out.println(book));

// Checking if an element exists


if (books.contains("1984")) {
System.out.println("1984 is in the collection.");
}
// Removing an Element
books.remove("1984");
System.out.println("After removing 1984, books in the
collection: " + books);

// Checking the Size of the TreeSet


System.out.println("Size of the collection: " + books.size());

// Clearing the TreeSet


books.clear();
System.out.println("After clearing, size of the collection: " +
books.size()); // Output: 0
}
}
OUTPUT:
5.Vector
A Vector in Java is a part of the java.util package and implements the
List interface, which means it can grow or shrink in size dynamically.
Vectors are similar to ArrayList, but with a few key differences,
particularly in terms of synchronization.
Key Features of Vector
1. Resizable Array: Internally, a Vector uses a dynamically
resizable array to store its elements.
2. Synchronization: Vectors are synchronized, meaning they are
thread-safe. Multiple threads can access a Vector without
causing data corruption.
3. Indexed Access: Elements in a Vector can be accessed via an
index, providing fast random access to elements.
4. Legacy Class: Though part of the original java.util package,
Vector has been largely replaced by more modern collections
like ArrayList due to performance considerations.
5. Automatic Growth: When the internal array becomes full, a
Vector automatically increases its capacity, typically doubling its
size.
Performance Considerations
• Vectors might not perform as well as ArrayList in single-
threaded scenarios because of synchronization overhead.
• If thread safety is not required, using ArrayList is generally
recommended for better performance.
Common Use Cases
• Thread-Safe Operations: Suitable for applications where
thread-safe operations on lists are essential.
• Legacy Systems: Often used in older applications that were
built before the introduction of more modern collections like
ArrayList.

Operations on Vector:
Importing Vector:
import java.util.Vector;
With Generics:
Vector<String> books = new Vector<>();
Without Generics:
Vector books = new Vector();
Adding Elements:
books.add("Moby Dick");
Accessing Elements:
System.out.println("First Book: " + books.get(0)); // Access by index
Modifying Elements:
books.set(0, "Brave New World"); // Update the first element
Removing Elements:
books.remove("1984"); // Removes the element "1984"
Iterating without Lambda Expression:
for (Object book : books) {
System.out.println(book);
}
Iterating with Lambda Expression:
books.forEach(book -> System.out.println(book));
Checking for an Element:
if (books.contains("To Kill a Mockingbird")) {
System.out.println("To Kill a Mockingbird is in the collection.");
}
Clearing the Vector:
books.clear(); System.out.println("After clearing, size of the
collection: " + books.size()); // Output: 0
Implementation of Vector with Generics and Lambda
Expressions:
import java.util.Vector;

public class VectorWithGenerics {


public static void main(String[] args) {
Vector<String> books = new Vector<>();
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");
System.out.println("First Book: " + books.get(0));
books.set(0, "Brave New World");
System.out.println("Updated collection: " + books);
System.out.println("Books in the collection:");
books.forEach(book -> System.out.println(book));
if (books.contains("1984")) {
System.out.println("1984 is in the collection.");
}
books.remove("1984");
System.out.println("After removing 1984, books in the
collection: " + books);
System.out.println("Size of the collection: " + books.size());
books.clear();
System.out.println("After clearing, size of the collection: " +
books.size());
}
}
OUTPUT:
Implementation of Vector without Generics:
import java.util.Vector;

public class VectorWithGenerics {


public static void main(String[] args) {
Vector books = new Vector();
books.add("Moby Dick");
books.add("1984");
books.add("To Kill a Mockingbird");
System.out.println("First Book: " + books.get(0));
books.set(0, "Brave New World");
System.out.println("Updated collection: " + books);
System.out.println("Books in the collection:");
books.forEach(book -> System.out.println(book));
if (books.contains("1984")) {
System.out.println("1984 is in the collection.");
}
books.remove("1984");
System.out.println("After removing 1984, books in the
collection: " + books);
System.out.println("Size of the collection: " + books.size());
books.clear();
System.out.println("After clearing, size of the collection: " +
books.size());
}
}
OUTPUT:

RESULT:
The study on different collection classes are done successfully.

You might also like