Java_Collections_Scenarios
Java_Collections_Scenarios
1.1 .add()
Scenario: A student selects courses for registration. The selected courses need to be added
to their registration list. This can be done using the .add() method.
Code:
import java.util.*;
1.2 .get(index)
Scenario: After registration, the student wants to see the second course they enrolled in.
Code:
String secondCourse = courseList.get(1);
System.out.println("Second Enrolled Course: " + secondCourse);
Code:
1.4 .remove()
Scenario: The student drops the course ‘Computer Networks’.
Code:
courseList.remove("Computer Networks");
System.out.println("Updated Course List: " + courseList);
1.5 .contains()
Scenario: Before adding a course, check if the student is already enrolled.
Code:
if (courseList.contains("Data Structures")) {
System.out.println("Already Enrolled in Data Structures");
} else {
courseList.add("Data Structures");
}
2.1 .add()
Scenario: The system tracks unique email addresses for a newsletter subscription. When a
user subscribes, their email should be added.
Code:
Output: [[email protected]]
2.2 .contains()
Scenario: Check if an email is already subscribed.
Code:
System.out.println(emails.contains("[email protected]"));
Output: true
2.3 .remove()
Scenario: A user unsubscribes from the newsletter.
Code:
emails.remove("[email protected]");
System.out.println(emails);
Output: []
3.1 .put()
Scenario: Store student information with their ID and name.
Code:
Map<Integer, String> students = new HashMap<>();
students.put(1001, "Alice");
students.put(1002, "Bob");
System.out.println(students);
3.2 .get()
Scenario: Retrieve the name of the student with a specific ID.
Code:
System.out.println(students.get(1001));
Output: Alice
3.3 .remove()
Scenario: Remove a student who has left the school.
Code:
students.remove(1002);
System.out.println(students);
Output: {1001=Alice}
4.1 .add()
Scenario: People enter a queue at a bank. The first person in line is served first.
Code:
4.2 .poll()
Scenario: The first person in line is served.
Code:
System.out.println(queue.poll());
System.out.println(queue);
Output: Person1
[Person2]
4.3 .peek()
Scenario: See who is next in line.
Code:
System.out.println(queue.peek());
Output: Person2
5.1 .push()
Scenario: You open a series of web pages in a browser. The last opened tab should be the
first to close.
Code:
5.2 .pop()
Scenario: Close the last opened tab (About).
Code:
System.out.println(browserTabs.pop());
System.out.println(browserTabs);
Output: About
[Home]
5.3 .peek()
Scenario: See which tab is currently open.
Code:
System.out.println(browserTabs.peek());
Output: Home
6.1 .put()
Scenario: Store phone numbers of employees in a company directory.
Code:
6.2 .get()
Scenario: Retrieve the phone number of a specific employee.
Code:
System.out.println(phoneBook.get("John"));
Output: 123-456-7890