I/O Streams and Collections

I/O streams in java

1. Types of Streams

Java I/O streams are categorized into two main types:

  • Byte Streams: These handle I/O of raw binary data. They are used for reading and writing binary files, and their classes use byte-oriented methods. Examples include:
    • InputStream and OutputStream (abstract base classes)
    • FileInputStream and FileOutputStream
    • BufferedInputStream and BufferedOutputStream
  • Character Streams: These handle I/O of characters, which means they are used for reading and writing text files. They use character-oriented methods and handle character encoding. Examples include:
    • Reader and Writer (abstract base classes)
    • FileReader and FileWriter
    • BufferedReader and BufferedWriter

2. Basic Operations

  • Reading Data:
    • For byte streams, you can use methods like read() to read a byte or an array of bytes.
    • For character streams, you can use methods like read() to read a character or an array of characters.
  • Writing Data:
    • For byte streams, you use methods like write() to write bytes or byte arrays.
    • For character streams, you use methods like write() to write characters or character arrays.

3. Common Classes

  • FileInputStream/FileOutputStream: Used for reading from and writing to files in binary mode.
  • FileReader/FileWriter: Used for reading from and writing to files in character mode.
  • BufferedReader/BufferedWriter: Used to efficiently read and write text data using buffering.

Various File Access operations by using File Streams and a sample Program

File operations

File operations in Java involve various tasks such as creating, reading, writing, deleting, and manipulating files. The java.io package provides classes for file handling, but starting from Java 7, the java.nio.file package introduced a more modern and flexible file I/O API. Below, I’ll cover common file operations using both java.io and java.nio.file.

File class methods

MethodDescriptionExample
boolean createNewFile()Creates a new file. Returns true if the file was created; false if the file already exists.java File file = new File("example.txt"); if (file.createNewFile()) { ... }
boolean mkdir()Creates a directory. Returns true if the directory was created; false if it already exists or creation failed.java File dir = new File("exampleDir"); if (dir.mkdir()) { ... }
boolean mkdirs()Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if successful.java File dir = new File("exampleDir/subDir"); if (dir.mkdirs()) { ... }
boolean delete()Deletes the file or directory. Returns true if the file or directory was successfully deleted; false otherwise.java File file = new File("example.txt"); if (file.delete()) { ... }
boolean exists()Tests whether the file or directory exists.java File file = new File("example.txt"); if (file.exists()) { ... }
boolean isFile()Tests whether the file is a normal file.java File file = new File("example.txt"); if (file.isFile()) { ... }
boolean isDirectory()Tests whether the file is a directory.java File dir = new File("exampleDir"); if (dir.isDirectory()) { ... }
long length()Returns the length of the file in bytes. Returns 0 for directories.java File file = new File("example.txt"); long size = file.length();
String getName()Returns the name of the file or directory.java File file = new File("example.txt"); String name = file.getName();
String getAbsolutePath()Returns the absolute path of the file or directory.java File file = new File("example.txt"); String path = file.getAbsolutePath();
String getParent()Returns the parent directory of the file or directory. Returns null if there is no parent.java File file = new File("exampleDir/example.txt"); String parent = file.getParent();
File[] listFiles()Returns an array of File objects representing the files and directories in the directory. Returns null if the file is not a directory.java File dir = new File("exampleDir"); File[] files = dir.listFiles();
String[] list()Returns an array of String representing the names of the files and directories in the directory. Returns null if the file is not a directory.java File dir = new File("exampleDir"); String[] files = dir.list();

1.Create a File

Creating a file in Java involves using the java.io.File class or the java.nio.file.Files class. Here’s a detailed explanation of how to create a file using both methods:

1. Using java.io.File

The java.io.File class provides the createNewFile() method to create a new file.

Steps to Create a File Using java.io.File

1.Import the Required Package:

import java.io.File;
import java.io.IOException;

2.Create a File Object: Initialize a File object with the path of the file you want to create.

File file = new File("example.txt");

3.Create the File: Use the createNewFile() method to create the file. This method returns true if the file was created successfully and false if the file already exists.

try {
    if (file.createNewFile()) {
        System.out.println("File created: " + file.getName());
    } else {
        System.out.println("File already exists.");
    }
} catch (IOException e) {
    e.printStackTrace();
}

IOException: This exception is thrown if an I/O error occurs, such as a file already existing or a directory being incorrectly used as a file.

Example Program

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
public static void main(String[] args) {
// Specify the file path
File file = new File("example.txt");

// Create the file
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

To Get file Information

To get file information in Java, you typically use the java.io.File class.
Here, I’ll provide an example using both approaches to get file size, last modified date, and file permissions.

Using java.io.File

Here’s how you can get file information using java.io.File:

example

import java.io.File;
import java.text.SimpleDateFormat;

public class FileInfoExample {
    public static void main(String[] args) {
        // Specify the path to the file
        String filePath = "example.txt";
        File file = new File(filePath);

        // Check if the file exists
        if (file.exists()) {
            // File size in bytes
            long fileSize = file.length();
            
            // Last modification time
            long lastModified = file.lastModified();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastModifiedDate = sdf.format(lastModified);
            
            // File permissions
            boolean canRead = file.canRead();
            boolean canWrite = file.canWrite();
            boolean canExecute = file.canExecute();
            
            System.out.println("File Size: " + fileSize + " bytes");
            System.out.println("Last Modified: " + lastModifiedDate);
            System.out.println("Readable: " + canRead);
            System.out.println("Writable: " + canWrite);
            System.out.println("Executable: " + canExecute);
        } else {
            System.out.println("The file does not exist.");
        }
    }
}

Detailed Explanation

  1. Import Classes
    • import java.io.File;:
      Provides the File class to work with file and directory paths.
    • import java.text.SimpleDateFormat;:
      Used to format the last modified date into a readable string.
  2. Specify File Path
    • String filePath = "example.txt";:
      Path to the file you want to inspect.
  3. Create File Object
    • File file = new File(filePath);:
      Creates a File object representing the file.
  4. Check if File Exists
    • if (file.exists()):
      Checks if the file exists to prevent errors.
  5. Get File Size
    • long fileSize = file.length();:
      Returns the file size in bytes.
  6. Get Last Modified Time
    • long lastModified = file.lastModified();:
    • Returns the last modification time as a timestamp.
    • SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");:
      Defines the format for the date.
    • String lastModifiedDate = sdf.format(lastModified);:
      Converts the timestamp to a readable date format.
  7. Check File Permissions
    • file.canRead(): Checks if the file is readable.
    • file.canWrite(): Checks if the file is writable.
    • file.canExecute(): Checks if the file is executable.
  8. Print Results
    • Outputs the file size, last modification date, and permissions.

Write to a file

Writing to a file in Java can be done using either java.io
. Here are examples of how to write data to a file using both approaches:

Using java.io.FileWriter

import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {
public static void main(String[] args) {
// Specify the path to the file
String filePath = "example.txt";

// Data to write to the file
String data = "Hello, World!\nThis is a sample text.";

try (FileWriter writer = new FileWriter(filePath)) {
// Write data to the file
writer.write(data);
System.out.println("Data written to " + filePath);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

Detailed Explanation

  1. Import Classes
    • import java.io.FileWriter;:
      Provides the FileWriter class for writing characters to a file.
    • import java.io.IOException;:
      Handles input and output exceptions.
  2. Specify File Path
    • String filePath = "example.txt";:
      Path where you want to create or open the file.
  3. Data to Write
    • String data = "Hello, World!\nThis is a sample text.";:
      Data to be written to the file.
  4. Open File and Write Data
    • try (FileWriter writer = new FileWriter(filePath)):
      Opens the file in write mode. The try-with-resources statement ensures that the file is closed automatically after the block is executed.
    • writer.write(data);:
      Writes the specified data to the file.
  5. Handle Exceptions
    • catch (IOException e):
      Catches and handles any IO exceptions that occur during file operations.

Read from a File

Reading from a file in Java can be accomplished using either the java.io
Here are examples for both approaches.

Using java.io.BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReadExample {
public static void main(String[] args) {
// Specify the path to the file
String filePath = "example.txt";

// Read the file content
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

Detailed Explanation

  1. Import Classes
    • import java.io.BufferedReader;:
      Provides a buffered input stream to read text efficiently.
    • import java.io.FileReader;:
      Used to open the file.
    • import java.io.IOException;:
      Handles IO exceptions.
  2. Specify File Path
    • String filePath = "example.txt";:
      Path to the file you want to read.
  3. Read File Content
    • try (BufferedReader reader = new BufferedReader(new FileReader(filePath))):
      Opens the file using FileReader wrapped in BufferedReader for efficient reading. The try-with-resources statement ensures that the file is closed automatically.
    • String line; while ((line = reader.readLine()) != null):
      Reads the file line by line. readLine() returns null when the end of the file is reached.
    • System.out.println(line);:
      Prints each line to the console.
  4. Handle Exceptions
    • catch (IOException e):
      Catches and handles any IO exceptions.

Delete a file

To delete a file in Java, you can use either the java.io.File class . Below are examples for both approaches:

Using java.io.File

import java.io.File;

public class FileDeleteExample {
public static void main(String[] args) {
// Specify the path to the file
String filePath = "example.txt";
File file = new File(filePath);

// Delete the file
if (file.exists()) {
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
} else {
System.out.println("The file does not exist.");
}
}
}

Detailed Explanation

  1. Import Classes
    • import java.io.File;:
      Provides the File class for file operations.
  2. Specify File Path
    • String filePath = "example.txt";:
      Path to the file you want to delete.
  3. Create File Object
    • File file = new File(filePath);:
      Creates a File object representing the file.
  4. Check if File Exists
    • if (file.exists()):
      Checks if the file exists to avoid trying to delete a non-existent file.
  5. Delete File
    • if (file.delete()):
      Deletes the file. Returns true if the file was successfully deleted, false otherwise.
  6. Handle Results
    • Prints a success or failure message based on the result of the delete operation.

Collection Framework

The Java Collection Framework is a set of classes and interfaces that provide a standardized way to handle collections of objects. It is part of the java.util package and is designed to manage groups of objects in a convenient and efficient manner. Here’s an overview of the key components:

1. Core Interfaces

  • Collection: The root interface in the collection hierarchy. It represents a group of objects, known as elements. Common methods include add(), remove(), and size().
    • List: An interface that represents an ordered collection (sequence) of elements. Lists allow duplicates and provide precise control over where each element is inserted. Key implementations are ArrayList and LinkedList.
    • Set: An interface that represents a collection that does not allow duplicate elements. Sets are used to model mathematical sets. Key implementations are HashSet and TreeSet.
    • Queue: An interface that represents a collection designed for holding elements prior to processing. It supports operations like insertion, removal, and inspection. Key implementations are LinkedList and PriorityQueue.
    • Deque: An interface that represents a double-ended queue, which supports element insertion and removal from both ends. Key implementations are ArrayDeque and LinkedList.
  • Map: An interface that maps keys to values, where each key is associated with exactly one value. Maps do not allow duplicate keys. Key implementations are HashMap, TreeMap, and LinkedHashMap.

2. Key Classes

  • ArrayList: A resizable array implementation of the List interface. It provides fast access to elements via indices but can be slow for insertions and deletions.
  • LinkedList: A doubly-linked list implementation of the List and Deque interfaces. It is efficient for insertions and deletions but slower for access operations compared to ArrayList.
  • HashSet: A Set implementation backed by a hash table. It provides constant-time performance for basic operations and does not guarantee the order of elements.
  • TreeSet: A Set implementation that uses a red-black tree. It provides a sorted order of elements and guarantees log-time performance for basic operations.
  • PriorityQueue: An implementation of the Queue interface that uses a priority heap. Elements are ordered based on their natural ordering or by a comparator provided at queue construction time.
  • HashMap: A Map implementation that uses a hash table. It provides constant-time performance for basic operations and does not guarantee any specific order of elements.
  • TreeMap: A Map implementation that uses a red-black tree. It provides a sorted order of keys and guarantees log-time performance for basic operations.

3. Key Concepts

  • Generics: The collection framework uses generics to provide type safety and eliminate the need for casting. For example, List<String> ensures that only String objects can be added to the list.
  • Iteration: Collections can be traversed using iterators. The Iterator interface provides methods like hasNext(), next(), and remove() to iterate over elements.
  • Algorithms: The Collections class provides static methods for common algorithms such as sorting and searching, which can be applied to collections.
  • Concurrent Collections: The java.util.concurrent package provides thread-safe collections like ConcurrentHashMap and CopyOnWriteArrayList for concurrent access.

4. Use Cases

  • Lists: Used when you need an ordered collection with possible duplicate elements. Examples include maintaining a sequence of elements or managing a list of user inputs.
  • Sets: Used when you need to ensure that a collection contains unique elements. Examples include removing duplicates from a collection or checking membership.
  • Queues: Used for managing elements that need to be processed in a specific order. Examples include task scheduling and buffering.
  • Maps: Used when you need to associate keys with values. Examples include implementing lookup tables and caching.

The Java Collection Framework provides a powerful and flexible way to handle and manipulate collections of objects, making it easier to work with data structures in Java.

Sample Programs

Array List :

    import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList bhanuFruits = new ArrayList<>();
// Add elements
    bhanuFruits.add("Apple");
    bhanuFruits.add("Banana");
    bhanuFruits.add("Cherry");

    // Print initial list
    System.out.println("Bhanu's Fruits: " + bhanuFruits);

    // Modify an element
    bhanuFruits.set(1, "Blueberry");
    System.out.println("After modification: " + bhanuFruits);

    // Remove an element
    bhanuFruits.remove("Cherry");
    System.out.println("After removal: " + bhanuFruits);

    // Check if an element exists
    System.out.println("Contains 'Apple': " + bhanuFruits.contains("Apple"));

    // Print size and iterate through the list
    System.out.println("Size: " + bhanuFruits.size());
    for (String fruit : bhanuFruits) {
        System.out.println(fruit);
    }

    // Clear all elements
    bhanuFruits.clear();
    System.out.println("After clearing: " + bhanuFruits);
}
}

Explanation

  1. Import the ArrayList Class
    • import java.util.ArrayList;: Imports the ArrayList class from the Java Collections Framework.
  2. Create an ArrayList
    • ArrayList<String> bhanuFruits = new ArrayList<>();: Creates an ArrayList named bhanuFruits that stores String elements.
  3. Add Elements
    • bhanuFruits.add("Apple");: Adds “Apple” to the list.
    • bhanuFruits.add("Banana");: Adds “Banana” to the list.
    • bhanuFruits.add("Cherry");: Adds “Cherry” to the list.
  4. Print Initial List
    • System.out.println("Bhanu's Fruits: " + bhanuFruits);: Displays the contents of the list.
  5. Modify an Element
    • bhanuFruits.set(1, "Blueberry");: Changes the element at index 1 from “Banana” to “Blueberry”.
    • System.out.println("After modification: " + bhanuFruits);: Prints the list after modification.
  6. Remove an Element
    • bhanuFruits.remove("Cherry");: Removes “Cherry” from the list.
    • System.out.println("After removal: " + bhanuFruits);: Prints the list after removal.
  7. Check for an Element
    • System.out.println("Contains 'Apple': " + bhanuFruits.contains("Apple"));: Checks if “Apple” is in the list and prints the result.
  8. Print Size and Iterate
    • System.out.println("Size: " + bhanuFruits.size());: Displays the number of elements in the list.
    • for (String fruit : bhanuFruits): Iterates through each element and prints it.
  9. Clear All Elements
    • bhanuFruits.clear();: Removes all elements from the list.
    • System.out.println("After clearing: " + bhanuFruits);: Prints the empty list after clearing.

This compact version maintains the core functionality and demonstrates key ArrayList operations with explanations.

Linked List:

import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a LinkedList of Strings
        LinkedList<String> bhanuLinkedList = new LinkedList<>();

        // Add elements
        bhanuLinkedList.add("Apple");
        bhanuLinkedList.add("Banana");
        bhanuLinkedList.add("Cherry");

        // Print the LinkedList
        System.out.println("Bhanu's LinkedList: " + bhanuLinkedList);

        // Modify an element
        bhanuLinkedList.set(1, "Blueberry");
        System.out.println("After modification: " + bhanuLinkedList);

        // Remove an element
        bhanuLinkedList.remove("Cherry");
        System.out.println("After removal: " + bhanuLinkedList);

        // Check if an element exists
        System.out.println("Contains 'Apple': " + bhanuLinkedList.contains("Apple"));

        // Print size and iterate through the list
        System.out.println("Size: " + bhanuLinkedList.size());
        for (String fruit : bhanuLinkedList) {
            System.out.println(fruit);
        }

        // Clear all elements
        bhanuLinkedList.clear();
        System.out.println("After clearing: " + bhanuLinkedList);
    }
}

Explanation

  1. Import the LinkedList Class
    • import java.util.LinkedList;: Imports the LinkedList class from the Java Collections Framework.
  2. Create a LinkedList
    • LinkedList<String> bhanuLinkedList = new LinkedList<>();: Creates a LinkedList named bhanuLinkedList that stores String elements.
  3. Add Elements
    • bhanuLinkedList.add("Apple");: Adds “Apple” to the end of the list.
    • bhanuLinkedList.add("Banana");: Adds “Banana” to the end of the list.
    • bhanuLinkedList.add("Cherry");: Adds “Cherry” to the end of the list.
  4. Print the LinkedList
    • System.out.println("Bhanu's LinkedList: " + bhanuLinkedList);: Displays the contents of the list.
  5. Modify an Element
    • bhanuLinkedList.set(1, "Blueberry");: Changes the element at index 1 from “Banana” to “Blueberry”.
    • System.out.println("After modification: " + bhanuLinkedList);: Prints the list after modification.
  6. Remove an Element
    • bhanuLinkedList.remove("Cherry");: Removes the first occurrence of “Cherry” from the list.
    • System.out.println("After removal: " + bhanuLinkedList);: Prints the list after removal.
  7. Check for an Element
    • System.out.println("Contains 'Apple': " + bhanuLinkedList.contains("Apple"));: Checks if “Apple” is in the list and prints the result.
  8. Print Size and Iterate
    • System.out.println("Size: " + bhanuLinkedList.size());: Displays the number of elements in the list.
    • for (String fruit : bhanuLinkedList): Iterates through each element and prints it.
  9. Clear All Elements
    • bhanuLinkedList.clear();: Removes all elements from the list.
    • System.out.println("After clearing: " + bhanuLinkedList);: Prints the empty list after clearing.

Summary

  • LinkedList is a data structure that uses a doubly linked list to store elements.
  • It allows efficient insertion and removal of elements from both ends and is suitable for scenarios where such operations are frequent.
  • It provides methods similar to ArrayList, including adding, modifying, removing, and checking elements.

Iterator and List Iterator Interface Methods and a Sample Program

The Iterator interface in Java provides a way to iterate over elements of a collection. It is part of the java.util package and offers methods to traverse, remove elements, and check the iteration state.

Key Methods of Iterator

  • boolean hasNext(): Returns true if the iteration has more elements.
  • E next(): Returns the next element in the iteration.
  • void remove(): Removes the last element returned by the iterator.

Sample Program Using Iterator

Here’s a sample program that demonstrates the use of the Iterator interface with an ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> bhanuList = new ArrayList<>();
bhanuList.add("Apple");
bhanuList.add("Banana");
bhanuList.add("Cherry");

// Using Iterator
System.out.println("Using Iterator:");

// Get an Iterator for the ArrayList
Iterator<String> iterator = bhanuList.iterator();

// Iterate through the list
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}

// Remove an element using Iterator
// Reset the iterator to demonstrate removal
iterator = bhanuList.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
if ("Banana".equals(fruit)) {
iterator.remove(); // Remove "Banana" from the list
}
}

// Print the list after removal
System.out.println("\nAfter removal:");
for (String fruit : bhanuList) {
System.out.println(fruit);
}
}
}

Explanation

  1. Create and Populate ArrayList
    • ArrayList<String> bhanuList = new ArrayList<>();: Creates an ArrayList of String.
    • bhanuList.add(...): Adds elements to the list.
  2. Using Iterator
    • Iterator<String> iterator = bhanuList.iterator();: Gets an Iterator for the list.
    • Iteration:
      • while (iterator.hasNext()): Checks if there are more elements.
      • String fruit = iterator.next();: Retrieves the next element.
      • System.out.println(fruit);: Prints each element.
  3. Remove an Element Using Iterator
    • Reinitialize Iterator: A new iterator is needed for removal after the first iteration.
    • if ("Banana".equals(fruit)): Checks if the current element is “Banana”.
    • iterator.remove();: Removes “Banana” from the list.
  4. Print Modified List
    • Final Print: Iterates through the modified list and prints the remaining elements.

Summary

  • hasNext(): Checks if there are more elements to iterate over.
  • next(): Retrieves the next element.
  • remove(): Removes the last element returned by the iterator.

This example demonstrates the basic usage of Iterator for traversing and modifying a collection, showing its primary methods in action.

List Iterator interface

The ListIterator interface in Java extends the Iterator interface and provides additional capabilities for iterating over lists. It is available in the java.util package and is specific to lists, such as ArrayList and LinkedList. The ListIterator interface allows for bidirectional traversal, element modification, and insertion.

Key Methods of ListIterator

  1. Bidirectional Traversal
    • boolean hasNext(): Returns true if there are more elements when traversing forward.
    • E next(): Returns the next element in the list.
    • boolean hasPrevious(): Returns true if there are more elements when traversing backward.
    • E previous(): Returns the previous element in the list.
  2. Indexing
    • int nextIndex(): Returns the index of the element that would be returned by next().
    • int previousIndex(): Returns the index of the element that would be returned by previous().
  3. Modification
    • void remove(): Removes the last element returned by next() or previous().
    • void set(E e): Replaces the last element returned by next() or previous() with the specified element.
    • void add(E e): Inserts the specified element into the list at the position returned by next() or previous().

Sample Program Using ListIterator

Here’s a sample program demonstrating the use of ListIterator with an ArrayList:

import java.util.ArrayList;
import java.util.ListIterator;

public class ListIteratorExample {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> bhanuList = new ArrayList<>();
bhanuList.add("Apple");
bhanuList.add("Banana");
bhanuList.add("Cherry");

// Using ListIterator
System.out.println("Using ListIterator:");

// Get a ListIterator for the ArrayList
ListIterator<String> listIterator = bhanuList.listIterator();

// Forward traversal
System.out.println("Forward traversal:");
while (listIterator.hasNext()) {
String fruit = listIterator.next();
System.out.println("Index " + listIterator.previousIndex() + ": " + fruit);
}

// Backward traversal
System.out.println("\nBackward traversal:");
while (listIterator.hasPrevious()) {
String fruit = listIterator.previous();
System.out.println("Index " + listIterator.nextIndex() + ": " + fruit);
}

// Modify an element using ListIterator
listIterator = bhanuList.listIterator();
while (listIterator.hasNext()) {
String fruit = listIterator.next();
if ("Banana".equals(fruit)) {
listIterator.set("Blueberry"); // Replace "Banana" with "Blueberry"
}
}

// Insert an element using ListIterator
listIterator.add("Date"); // Add "Date" at the current position

// Print the modified list
System.out.println("\nAfter modification and addition:");
for (String fruit : bhanuList) {
System.out.println(fruit);
}
}
}

Explanation

  1. Create and Populate ArrayList
    • ArrayList<String> bhanuList = new ArrayList<>();: Creates an ArrayList of String.
    • bhanuList.add(...): Adds elements to the list.
  2. Using ListIterator
    • ListIterator<String> listIterator = bhanuList.listIterator();: Gets a ListIterator for the list.
  3. Forward Traversal
    • while (listIterator.hasNext()): Iterates through the list from beginning to end.
    • listIterator.next(): Retrieves the next element.
    • listIterator.previousIndex(): Provides the index of the current element.
  4. Backward Traversal
    • while (listIterator.hasPrevious()): Iterates through the list from end to beginning.
    • listIterator.previous(): Retrieves the previous element.
    • listIterator.nextIndex(): Provides the index of the next element.
  5. Modify an Element
    • if ("Banana".equals(fruit)): Checks for the element “Banana”.
    • listIterator.set("Blueberry");: Replaces “Banana” with “Blueberry”.
  6. Insert an Element
    • listIterator.add("Date");: Adds “Date” at the current position.
  7. Print Modified List
    • Prints the list after modifications to show the changes.

Summary

  • ListIterator provides more functionality than Iterator, including bidirectional traversal, index retrieval, and element modification.
  • It is specifically designed for use with lists and supports operations such as adding and replacing elements.

This example demonstrates the use of ListIterator for both forward and backward traversal, as well as for modifying and adding elements to a list.

List Interface and Hashset and HashTable Class

List interface

The List interface in Java is a part of the Java Collections Framework and is a subtype of the Collection interface. It represents an ordered collection (also known as a sequence) of elements. The List interface allows for duplicate elements and provides positional access to elements, meaning you can access elements by their integer index.

Key Methods of List Interface

Here are some of the most commonly used methods provided by the List interface:

  1. Basic Operations
    • boolean add(E e): Adds the specified element to the end of the list.
    • void add(int index, E element): Inserts the specified element at the specified position in the list.
    • E remove(int index): Removes the element at the specified position in the list.
    • boolean remove(Object o): Removes the first occurrence of the specified element from the list.
    • E get(int index): Returns the element at the specified position in the list.
    • E set(int index, E element): Replaces the element at the specified position with the specified element.
    • int size(): Returns the number of elements in the list.
    • boolean isEmpty(): Returns true if the list contains no elements.
    • boolean contains(Object o): Returns true if the list contains the specified element.
    • void clear(): Removes all elements from the list.
  2. Sublist Operations
    • List<E> subList(int fromIndex, int toIndex): Returns a view of the portion of the list between fromIndex, inclusive, and toIndex, exclusive.
  3. Index-Based Operations
    • int indexOf(Object o): Returns the index of the first occurrence of the specified element.
    • int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element.

Example Code

Here’s a simple example demonstrating the use of the List interface with an ArrayList:

import java.util.ArrayList;
import java.util.List;

public class ListExample {
public static void main(String[] args) {
// Create a List of Strings
List<String> bhanuList = new ArrayList<>();

// Add elements
bhanuList.add("Apple");
bhanuList.add("Banana");
bhanuList.add("Cherry");

// Print the list
System.out.println("Initial List: " + bhanuList);

// Add element at a specific position
bhanuList.add(1, "Blueberry");
System.out.println("After adding Blueberry: " + bhanuList);

// Remove an element
bhanuList.remove("Cherry");
System.out.println("After removing Cherry: " + bhanuList);

// Access an element
String fruit = bhanuList.get(2);
System.out.println("Element at index 2: " + fruit);

// Modify an element
bhanuList.set(1, "Blackberry");
System.out.println("After modifying index 1: " + bhanuList);

// Get the size of the list
System.out.println("Size of the list: " + bhanuList.size());

// Check if the list contains an element
System.out.println("Contains 'Apple': " + bhanuList.contains("Apple"));

// Get index of an element
System.out.println("Index of 'Blackberry': " + bhanuList.indexOf("Blackberry"));

// Get a sublist
List<String> subList = bhanuList.subList(0, 2);
System.out.println("Sublist (0 to 2): " + subList);

// Clear the list
bhanuList.clear();
System.out.println("After clearing the list: " + bhanuList);
}
}

Explanation

  1. Create and Populate ArrayList
    • List<String> bhanuList = new ArrayList<>();: Creates a List instance using ArrayList.
    • bhanuList.add(...): Adds elements to the list.
  2. Add Element at Specific Position
    • bhanuList.add(1, "Blueberry");: Inserts “Blueberry” at index 1.
  3. Remove Element
    • bhanuList.remove("Cherry");: Removes the first occurrence of “Cherry”.
  4. Access and Modify Elements
    • String fruit = bhanuList.get(2);: Retrieves the element at index 2.
    • bhanuList.set(1, "Blackberry");: Replaces the element at index 1 with “Blackberry”.
  5. Get Size and Check for Elements
    • bhanuList.size();: Retrieves the number of elements in the list.
    • bhanuList.contains("Apple");: Checks if “Apple” is in the list.
  6. Get Index and Sublist
    • bhanuList.indexOf("Blackberry");: Finds the index of “Blackberry”.
    • bhanuList.subList(0, 2);: Retrieves a sublist from index 0 (inclusive) to index 2 (exclusive).
  7. Clear the List
    • bhanuList.clear();: Removes all elements from the list.

Summary

  • List Interface: Represents an ordered collection with index-based access.
  • Methods: Include adding, removing, accessing, modifying elements, and more.
  • Implementations: Common implementations include ArrayList, LinkedList, and Vector.

This example covers basic List operations and demonstrates how to use them effectively with an ArrayList.

Hashset

The HashSet class in Java is part of the Java Collections Framework and implements the Set interface. It represents a collection of elements that are not ordered and do not allow duplicate elements. HashSet uses a hash table for storing elements, which allows for fast insertion, deletion, and lookup operations.

Key Characteristics of HashSet

  1. No Duplicates: HashSet does not allow duplicate elements. If you try to add a duplicate element, it will not be added to the set.
  2. Unordered: The elements in a HashSet are not stored in any specific order. The order of elements may change over time.
  3. Fast Operations: Operations like add, remove, and contains are generally constant time (O(1)) due to the underlying hash table.
  4. Null Elements: HashSet allows the inclusion of a single null element.

Key Methods of HashSet

  • boolean add(E e): Adds the specified element to the set if it is not already present.
  • boolean remove(Object o): Removes the specified element from the set if it is present.
  • boolean contains(Object o): Returns true if the set contains the specified element.
  • int size(): Returns the number of elements in the set.
  • boolean isEmpty(): Returns true if the set contains no elements.
  • void clear(): Removes all elements from the set.
  • Iterator<E> iterator(): Returns an iterator over the elements in the set.

Example Code

Here’s a sample program that demonstrates the use of HashSet:

import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet of Strings
HashSet<String> bhanuSet = new HashSet<>();

// Add elements
bhanuSet.add("Apple");
bhanuSet.add("Banana");
bhanuSet.add("Cherry");
bhanuSet.add("Apple"); // Duplicate, will not be added

// Print the HashSet
System.out.println("HashSet: " + bhanuSet);

// Remove an element
bhanuSet.remove("Banana");
System.out.println("After removing 'Banana': " + bhanuSet);

// Check if an element is in the set
System.out.println("Contains 'Apple': " + bhanuSet.contains("Apple"));

// Check the size of the set
System.out.println("Size of the HashSet: " + bhanuSet.size());

// Iterate through the HashSet
System.out.println("Iterating through HashSet:");
Iterator<String> iterator = bhanuSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

// Clear all elements
bhanuSet.clear();
System.out.println("After clearing the HashSet: " + bhanuSet);
}
}

Explanation

  1. Create and Populate HashSet
    • HashSet<String> bhanuSet = new HashSet<>();: Creates a HashSet of String.
    • bhanuSet.add(...): Adds elements to the set. Duplicate elements (e.g., “Apple”) are not added.
  2. Print the HashSet
    • System.out.println("HashSet: " + bhanuSet);: Displays the contents of the set.
  3. Remove an Element
    • bhanuSet.remove("Banana");: Removes the element “Banana” from the set.
  4. Check for Element
    • System.out.println("Contains 'Apple': " + bhanuSet.contains("Apple"));: Checks if “Apple” is in the set.
  5. Get Size
    • System.out.println("Size of the HashSet: " + bhanuSet.size());: Prints the number of elements in the set.
  6. Iterate Through the Set
    • Iterator<String> iterator = bhanuSet.iterator();: Gets an iterator for the set.
    • Iteration: while (iterator.hasNext()) loops through and prints each element.
  7. Clear the Set
    • bhanuSet.clear();: Removes all elements from the set.

Summary

  • HashSet: A collection that does not allow duplicates and does not guarantee any order of elements.
  • Efficiency: Provides fast operations for adding, removing, and checking elements due to its hash table implementation.
  • Usage: Suitable for scenarios where you need to ensure that no duplicates are stored and order is not important.

Hash Table

The Hashtable class in Java is a part of the Java Collections Framework and is a collection that maps keys to values. It implements the Map interface and uses a hash table for storage. Although it is similar to HashMap, there are some key differences.

Key Characteristics of Hashtable

  1. Thread Safety: Hashtable is synchronized, meaning it is thread-safe and can be used in concurrent applications where multiple threads might access it simultaneously. However, this synchronization comes at the cost of performance compared to HashMap.
  2. Null Keys and Values: Hashtable does not allow null keys or values. Attempting to insert a null key or value will result in a NullPointerException.
  3. Ordered: Hashtable does not guarantee any order of elements. It is similar to HashMap in this respect.
  4. Legacy Class: Hashtable is part of the original version of Java and is considered somewhat outdated compared to newer implementations like HashMap and ConcurrentHashMap.

Key Methods of Hashtable

  • V put(K key, V value): Associates the specified value with the specified key in the table.
  • V get(Object key): Returns the value to which the specified key is mapped.
  • V remove(Object key): Removes the mapping for the specified key from the table if present.
  • boolean containsKey(Object key): Returns true if the table contains a mapping for the specified key.
  • boolean containsValue(Object value): Returns true if the table maps one or more keys to the specified value.
  • int size(): Returns the number of key-value mappings in the table.
  • boolean isEmpty(): Returns true if the table contains no key-value mappings.
  • void clear(): Removes all of the mappings from the table.
  • Enumeration<K> keys(): Returns an enumeration of the keys in the table.
  • Enumeration<V> elements(): Returns an enumeration of the values in the table.

Example Code

Here’s a sample program that demonstrates the use of Hashtable:

import java.util.Hashtable;
import java.util.Enumeration;

public class HashtableExample {
public static void main(String[] args) {
// Create a Hashtable
Hashtable<String, String> bhanuTable = new Hashtable<>();

// Add key-value pairs
bhanuTable.put("Apple", "Fruit");
bhanuTable.put("Carrot", "Vegetable");
bhanuTable.put("Milk", "Dairy");

// Print the Hashtable
System.out.println("Hashtable: " + bhanuTable);

// Get a value by key
String value = bhanuTable.get("Apple");
System.out.println("Value for key 'Apple': " + value);

// Remove an entry
bhanuTable.remove("Carrot");
System.out.println("After removing 'Carrot': " + bhanuTable);

// Check if a key exists
System.out.println("Contains key 'Milk': " + bhanuTable.containsKey("Milk"));

// Check if a value exists
System.out.println("Contains value 'Fruit': " + bhanuTable.containsValue("Fruit"));

// Get size
System.out.println("Size of the Hashtable: " + bhanuTable.size());

// Iterate over the keys and values
System.out.println("Iterating over keys and values:");
Enumeration<String> keys = bhanuTable.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
String val = bhanuTable.get(key);
System.out.println("Key: " + key + ", Value: " + val);
}

// Clear the Hashtable
bhanuTable.clear();
System.out.println("After clearing the Hashtable: " + bhanuTable);
}
}

Explanation

  1. Create and Populate Hashtable
    • Hashtable<String, String> bhanuTable = new Hashtable<>();: Creates a Hashtable instance.
    • bhanuTable.put(...): Adds key-value pairs to the table.
  2. Get Value by Key
    • String value = bhanuTable.get("Apple");: Retrieves the value associated with the key “Apple”.
  3. Remove an Entry
    • bhanuTable.remove("Carrot");: Removes the key-value pair for the key “Carrot”.
  4. Check for Key and Value
    • bhanuTable.containsKey("Milk");: Checks if the key “Milk” exists.
    • bhanuTable.containsValue("Fruit");: Checks if the value “Fruit” exists.
  5. Get Size
    • bhanuTable.size();: Retrieves the number of key-value mappings.
  6. Iterate Over Keys and Values
    • Enumeration<String> keys = bhanuTable.keys();: Gets an enumeration of the keys.
    • Iteration: while (keys.hasMoreElements()) loops through and prints each key and its associated value.
  7. Clear the Hashtable
    • bhanuTable.clear();: Removes all key-value pairs from the table.

Summary

  • Hashtable: A synchronized map implementation that does not allow null keys or values.
  • Legacy: Consider using HashMap or ConcurrentHashMap for better performance and flexibility in newer applications.
  • Usage: Suitable for scenarios requiring thread safety with synchronized access.

This example illustrates how to perform common operations with Hashtable, including adding, retrieving, removing entries, and iterating over key-value pairs.

Map Interface and HashMap class

map interface

The Map interface in Java is part of the Java Collections Framework and represents a collection of key-value pairs. It does not extend the Collection interface but is a key component in the framework for storing mappings of keys to values.

Key Characteristics of Map

  1. Key-Value Pairs: A Map stores mappings of keys to values. Each key is associated with exactly one value.
  2. Uniqueness of Keys: Each key in a Map is unique. If you try to add a duplicate key, the existing key-value pair will be replaced with the new one.
  3. Null Keys and Values: Some implementations of Map (like HashMap) allow null keys and values, while others (like Hashtable) do not.
  4. Order: The order of elements in a Map depends on the implementation. For example, LinkedHashMap maintains insertion order, while TreeMap sorts entries by keys.

Example Code

Here’s a simple example demonstrating the use of the Map interface with a HashMap:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Collection;

public class MapExample {
public static void main(String[] args) {
// Create a HashMap
Map<String, String> bhanuMap = new HashMap<>();

// Add key-value pairs
bhanuMap.put("Apple", "Fruit");
bhanuMap.put("Carrot", "Vegetable");
bhanuMap.put("Milk", "Dairy");

// Print the map
System.out.println("HashMap: " + bhanuMap);

// Get a value by key
String value = bhanuMap.get("Apple");
System.out.println("Value for key 'Apple': " + value);

// Remove an entry
bhanuMap.remove("Carrot");
System.out.println("After removing 'Carrot': " + bhanuMap);

// Check if a key exists
System.out.println("Contains key 'Milk': " + bhanuMap.containsKey("Milk"));

// Check if a value exists
System.out.println("Contains value 'Fruit': " + bhanuMap.containsValue("Fruit"));

// Get size
System.out.println("Size of the map: " + bhanuMap.size());

// Iterate over the map
System.out.println("Iterating over map entries:");
for (Map.Entry<String, String> entry : bhanuMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

// Get keys and values
Set<String> keys = bhanuMap.keySet();
Collection<String> values = bhanuMap.values();
System.out.println("Keys: " + keys);
System.out.println("Values: " + values);

// Clear the map
bhanuMap.clear();
System.out.println("After clearing the map: " + bhanuMap);
}
}

Explanation

  1. Create and Populate HashMap
    • Map<String, String> bhanuMap = new HashMap<>();: Creates a HashMap instance.
    • bhanuMap.put(...): Adds key-value pairs.
  2. Get and Remove Entries
    • String value = bhanuMap.get("Apple");: Retrieves the value for “Apple”.
    • bhanuMap.remove("Carrot");: Removes the entry for “Carrot”.
  3. Check for Key and Value
    • bhanuMap.containsKey("Milk");: Checks if “Milk” is a key.
    • bhanuMap.containsValue("Fruit");: Checks if “Fruit” is a value.
  4. Size and Iteration
    • bhanuMap.size();: Gets the number of entries.
    • Iterates through the entries with entrySet().
  5. Get Keys and Values
    • bhanuMap.keySet();: Retrieves all keys.
    • bhanuMap.values();: Retrieves all values.
  6. Clear the Map
    • bhanuMap.clear();: Removes all entries from the map.

Summary

  • Map Interface: Represents a collection of key-value pairs.
  • Methods: Includes operations for adding, removing, retrieving, and iterating over mappings.
  • Implementations: Common implementations include HashMap, LinkedHashMap, and TreeMap.

This example demonstrates how to use the Map interface and its common methods, providing a clear understanding of how to work with key-value pairs in Java.

HashMap Interface

The HashMap class in Java is a popular implementation of the Map interface. It provides a hash table-based implementation of the Map interface, allowing for efficient retrieval, insertion, and deletion of key-value pairs. Here’s a detailed overview of the HashMap class:

Key Characteristics of HashMap

  1. Non-Synchronized: HashMap is not synchronized, making it not thread-safe. For thread-safe operations, consider using ConcurrentHashMap.
  2. Allows Null Keys and Values: Unlike Hashtable, HashMap allows one null key and multiple null values.
  3. No Order Guarantee: The order of elements in a HashMap is not predictable. It does not maintain the order of insertion.
  4. Efficiency: Provides constant-time performance (O(1)) for basic operations like add, remove, and get, assuming the hash function disperses elements properly among buckets.

Example Code

Here’s a sample program demonstrating the use of HashMap:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Collection;

public class HashMapExample {
public static void main(String[] args) {
// Create a HashMap
Map<String, String> hashMap = new HashMap<>();

// Add key-value pairs
hashMap.put("Apple", "Fruit");
hashMap.put("Carrot", "Vegetable");
hashMap.put("Milk", "Dairy");
hashMap.put(null, "NullValue"); // Null key allowed
hashMap.put("Cheese", null); // Null value allowed

// Print the HashMap
System.out.println("HashMap: " + hashMap);

// Get a value by key
String value = hashMap.get("Apple");
System.out.println("Value for key 'Apple': " + value);

// Remove an entry
hashMap.remove("Carrot");
System.out.println("After removing 'Carrot': " + hashMap);

// Check if a key exists
System.out.println("Contains key 'Milk': " + hashMap.containsKey("Milk"));

// Check if a value exists
System.out.println("Contains value 'Fruit': " + hashMap.containsValue("Fruit"));

// Get size
System.out.println("Size of the HashMap: " + hashMap.size());

// Iterate over the HashMap
System.out.println("Iterating over map entries:");
for (Map.Entry<String, String> entry : hashMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

// Get keys and values
Set<String> keys = hashMap.keySet();
Collection<String> values = hashMap.values();
System.out.println("Keys: " + keys);
System.out.println("Values: " + values);

// Clear the HashMap
hashMap.clear();
System.out.println("After clearing the HashMap: " + hashMap);
}
}

Explanation

  1. Create and Populate HashMap
    • Map<String, String> hashMap = new HashMap<>();: Creates a HashMap instance.
    • hashMap.put(...): Adds key-value pairs. Allows one null key and multiple null values.
  2. Get and Remove Entries
    • String value = hashMap.get("Apple");: Retrieves the value associated with “Apple”.
    • hashMap.remove("Carrot");: Removes the entry with key “Carrot”.
  3. Check for Key and Value
    • hashMap.containsKey("Milk");: Checks if the key “Milk” exists.
    • hashMap.containsValue("Fruit");: Checks if the value “Fruit” is present.
  4. Size and Iteration
    • hashMap.size();: Gets the number of entries in the map.
    • Iteration: Loops through entries using entrySet().
  5. Get Keys and Values
    • hashMap.keySet();: Retrieves all keys.
    • hashMap.values();: Retrieves all values.
  6. Clear the Map
    • hashMap.clear();: Removes all entries.

Summary

  • HashMap: A hash table-based implementation of the Map interface.
  • Characteristics: Allows one null key and multiple null values; not synchronized.
  • Methods: Provides methods for basic map operations, size checking, presence checking, and obtaining views of keys and values.

This overview and example should provide a solid understanding of how to use HashMap effectively in Java.

EnumSet and EnumMap classes

EnumSet:

EnumSet is a specialized implementation of the Set interface in Java, designed specifically for use with enum types. It is part of the java.util package and is optimized for enums, offering high performance and a compact representation.

Key Characteristics of EnumSet

  1. Specialized for Enums: EnumSet can only be used with enum types. It is not compatible with other types.
  2. Performance: Provides high-performance operations for enum sets, typically faster than other Set implementations.
  3. Implementation: Internally uses bit vectors to store the elements, which makes it very efficient in terms of both time and space.
  4. Order: Maintains the natural order of enum constants as defined by the enum type. The order is the same as the order in which the enum constants are declared in the enum type.
  5. Methods: Inherits methods from the Set interface and also provides some additional methods tailored for enums.

Example Code

Here’s a sample program demonstrating the use of EnumSet:

import java.util.EnumSet;

enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class EnumSetExample {
public static void main(String[] args) {
// Create an EnumSet with all days
EnumSet<Day> allDays = EnumSet.allOf(Day.class);
System.out.println("All days: " + allDays);

// Create an EnumSet with specific days
EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
System.out.println("Weekend days: " + weekend);

// Create an EnumSet with a range of days
EnumSet<Day> workDays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
System.out.println("Work days: " + workDays);

// Create an empty EnumSet
EnumSet<Day> emptySet = EnumSet.noneOf(Day.class);
System.out.println("Empty set: " + emptySet);

// Add and remove elements
emptySet.add(Day.MONDAY);
emptySet.add(Day.FRIDAY);
System.out.println("Set after adding days: " + emptySet);
emptySet.remove(Day.MONDAY);
System.out.println("Set after removing Monday: " + emptySet);

// Get complement of a set
EnumSet<Day> complementSet = EnumSet.complementOf(weekend);
System.out.println("Complement of weekend: " + complementSet);

// Clear the set
emptySet.clear();
System.out.println("Empty set after clear: " + emptySet);
}
}

Explanation

  1. Creating EnumSets
    • EnumSet.allOf(Day.class);: Creates an EnumSet with all enum constants.
    • EnumSet.of(Day.SATURDAY, Day.SUNDAY);: Creates an EnumSet with specific elements.
    • EnumSet.range(Day.MONDAY, Day.FRIDAY);: Creates an EnumSet with a range of enum constants.
  2. Operations
    • emptySet.add(Day.MONDAY);: Adds an element to the set.
    • emptySet.remove(Day.MONDAY);: Removes an element from the set.
  3. Complement and Clearing
    • EnumSet.complementOf(weekend);: Gets the complement of a given EnumSet.
    • emptySet.clear();: Clears all elements from the set.

Summary

  • EnumSet: A high-performance Set implementation for enum types.
  • Characteristics: Allows fast operations with enums, maintains natural order, and provides methods for creating sets with specific elements or ranges.
  • Methods: Includes creation, addition, removal, and special operations tailored for enum types.

This overview and example should provide a good understanding of how to use EnumSet effectively in Java.

EnumMap:

EnumMap is a specialized implementation of the Map interface in Java, specifically designed to work with enum keys. It is part of the java.util package and offers high performance and efficient storage for enum keys.

Key Characteristics of EnumMap

  1. Specialized for Enums: EnumMap is tailored for use with enum types as keys. It is not designed for use with other types.
  2. Performance: It provides efficient performance in terms of both time and space. It typically uses an array internally to store the values associated with enum keys, which ensures constant-time performance (O(1)) for basic operations.
  3. Order: EnumMap maintains the natural order of the enum constants as they are declared in the enum type.
  4. Null Keys: EnumMap does not allow null keys. Attempting to use null as a key will result in a NullPointerException.
  5. Implementation: Uses a compact and efficient array-based representation to store values, which makes it very efficient for enums.

Example Code

Here’s a sample program demonstrating the use of EnumMap:

import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
import java.util.Collection;

enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class EnumMapExample {
public static void main(String[] args) {
// Create an EnumMap with Day as the key type
EnumMap<Day, String> enumMap = new EnumMap<>(Day.class);

// Add key-value pairs
enumMap.put(Day.MONDAY, "Start of the week");
enumMap.put(Day.FRIDAY, "End of the work week");
enumMap.put(Day.SATURDAY, "Weekend");
enumMap.put(Day.SUNDAY, "Weekend");

// Print the EnumMap
System.out.println("EnumMap: " + enumMap);

// Get a value by key
String value = enumMap.get(Day.MONDAY);
System.out.println("Value for key 'MONDAY': " + value);

// Remove an entry
enumMap.remove(Day.SUNDAY);
System.out.println("After removing 'SUNDAY': " + enumMap);

// Check if a key exists
System.out.println("Contains key 'FRIDAY': " + enumMap.containsKey(Day.FRIDAY));

// Check if a value exists
System.out.println("Contains value 'Weekend': " + enumMap.containsValue("Weekend"));

// Get size
System.out.println("Size of the EnumMap: " + enumMap.size());

// Iterate over the EnumMap
System.out.println("Iterating over map entries:");
for (Map.Entry<Day, String> entry : enumMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

// Get keys and values
Set<Day> keys = enumMap.keySet();
Collection<String> values = enumMap.values();
System.out.println("Keys: " + keys);
System.out.println("Values: " + values);

// Clear the EnumMap
enumMap.clear();
System.out.println("After clearing the EnumMap: " + enumMap);
}
}

Explanation

  1. Creating EnumMaps
    • EnumMap<Day, String> enumMap = new EnumMap<>(Day.class);: Creates an EnumMap with Day enum as keys and String as values.
  2. Adding and Removing Entries
    • enumMap.put(Day.MONDAY, "Start of the week");: Adds key-value pairs to the map.
    • enumMap.remove(Day.SUNDAY);: Removes the entry for SUNDAY.
  3. Checking Key and Value Presence
    • enumMap.containsKey(Day.FRIDAY);: Checks if FRIDAY is a key in the map.
    • enumMap.containsValue("Weekend");: Checks if "Weekend" is a value in the map.
  4. Size and Iteration
    • enumMap.size();: Gets the number of entries in the map.
    • Iterates through entries using entrySet().
  5. Getting Keys and Values
    • enumMap.keySet();: Retrieves all keys.
    • enumMap.values();: Retrieves all values.
  6. Clearing the Map
    • enumMap.clear();: Removes all entries from the map.

Summary

  • EnumMap: A high-performance map implementation optimized for enum keys.
  • Characteristics: Allows efficient storage and retrieval with enums, maintains natural order, and disallows null keys.
  • Methods: Includes methods for basic map operations, as well as views of keys and values.

This overview and example should provide a solid understanding of how to use EnumMap effectively in Java.

I/O Streams and Collections

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top