Collection in Java
Each type of collection has its unique characteristics and is suitable for specific scenarios. Here’s a brief overview of the most common types of collections and when to use them:
Commonly Used Collections in Java:
1. ArrayList
Characteristics: An ordered collection of elements that supports indexing.
Use When: You need to maintain the order of elements and require frequent access by index. It can dynamically resize.
Example: Managing a list of students in a class.
2. HashSet
Characteristics: An unordered collection of unique elements without an index.
Use When: You need to ensure that all elements are unique, and the order of elements doesn’t matter.
Example: Keeping track of unique visitors to a website.
3. HashMap
Characteristics: A collection of key-value pairs, supports fast lookups by key.
Use When: You need to associate values with keys and perform fast lookups, additions, and deletions based on keys.
Example: Storing user profiles where the username is the key and the profile details are the value.
Examples to Illustrate Different Uses:
ArrayList Example:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add(“Alice”);
students.add(“Bob”);
System.out.println(students.get(0)); // Output: Alice
}
}
HashSet Example:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Integer> uniqueNumbers = new HashSet<>();
uniqueNumbers.add(2);
uniqueNumbers.add(1);
uniqueNumbers.add(2); // Duplicate, will not be added
System.out.println(uniqueNumbers.size()); // Output: 2
}
}
HashSet Example:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> ageMap = new HashMap<>();
ageMap.put(“Alice”, 25);
ageMap.put(“Bob”, 30);
System.out.println(ageMap.get(“Alice”)); // Output: 25
}
}
Project Scenarios
To-Do List Application (Using ArrayList):
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<String> toDoList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println(“\nTo-Do List Application”);
System.out.println(“1. Add Task”);
System.out.println(“2. Remove Task”);
System.out.println(“3. Display Tasks”);
System.out.println(“4. Exit”);
System.out.print(“Choose an option: “);
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print(“Enter a task to add: “);
String taskToAdd = scanner.nextLine();
toDoList.add(taskToAdd);
System.out.println(“Task added.”);
break;
case 2:
System.out.print(“Enter the task to remove: “);
String taskToRemove = scanner.nextLine();
if (toDoList.remove(taskToRemove)) {
System.out.println(“Task removed.”);
} else {
System.out.println(“Task not found.”);
}
break;
case 3:
System.out.println(“Current Tasks:”);
if (toDoList.isEmpty()) {
System.out.println(“No tasks in the list.”);
} else {
for (String task : toDoList) {
System.out.println(“- ” + task);
}
}
break;
case 4:
System.out.println(“Exiting application.”);
scanner.close();
return;
default:
System.out.println(“Invalid option. Please try again.”);
break;
}
}
}
}
Unique Visitor Tracker (Using HashSet):
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
HashSet<String> visitorIDs = new HashSet<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println(“\nUnique Visitor Tracker”);
System.out.println(“1. Add Visitor ID”);
System.out.println(“2. Display Unique Visitor IDs”);
System.out.println(“3. Exit”);
System.out.print(“Choose an option: “);
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print(“Enter a visitor ID to add: “);
String visitorID = scanner.nextLine();
if (visitorIDs.add(visitorID)) {
System.out.println(“Visitor ID added.”);
} else {
System.out.println(“Visitor ID already exists.”);
}
break;
case 2:
System.out.println(“Unique Visitor IDs:”);
if (visitorIDs.isEmpty()) {
System.out.println(“No visitor IDs in the set.”);
} else {
for (String id : visitorIDs) {
System.out.println(“- ” + id);
}
}
break;
case 3:
System.out.println(“Exiting application.”);
scanner.close();
return;
default:
System.out.println(“Invalid option. Please try again.”);
break;
}
}
}
}
User Profile Manager (Using HashMap):
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
HashMap<String, String> userProfiles = new HashMap<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println(“\nUser Profile Manager”);
System.out.println(“1. Add User Profile”);
System.out.println(“2. Retrieve User Profile”);
System.out.println(“3. Display All User Profiles”);
System.out.println(“4. Exit”);
System.out.print(“Choose an option: “);
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print(“Enter username: “);
String username = scanner.nextLine();
if (userProfiles.containsKey(username)) {
System.out.println(“Username already exists. Try another.”);
} else {
System.out.print(“Enter user details: “);
String userDetails = scanner.nextLine();
userProfiles.put(username, userDetails);
System.out.println(“User profile added.”);
}
break;
case 2:
System.out.print(“Enter username to retrieve: “);
String userToRetrieve = scanner.nextLine();
if (userProfiles.containsKey(userToRetrieve)) {
System.out.println(“User details for ” + userToRetrieve + “: ” + userProfiles.get(userToRetrieve));
} else {
System.out.println(“Username not found.”);
}
break;
case 3:
System.out.println(“All User Profiles:”);
if (userProfiles.isEmpty()) {
System.out.println(“No user profiles found.”);
} else {
for (var profile : userProfiles.entrySet()) {
System.out.println(profile.getKey() + “: ” + profile.getValue());
}
}
break;
case 4:
System.out.println(“Exiting application.”);
scanner.close();
return;
default:
System.out.println(“Invalid option. Please try again.”);
break;
}
}
}
}
Tasks:
Basic Operations:
Write a Java program to create a HashSet<Integer> and perform basic operations such as adding, removing, and checking for the presence of elements.
Add values: 12, 36, 47, 67, 69
Remove values: 36, 67
Check if 47 is present in the set.
Duplicate Removal:
Write a method that takes a List<Integer> as input and returns a new list with duplicates removed using a HashSet.
Input list: 7, 8, 7, 10, 10, 12, 15, 8
Basic Usage:
Write a Java program to create a HashMap<String, Integer> to store and display the names and ages of people. Include adding, updating, and removing entries.
Names and ages to add: “Alice” – 25, “Bob” – 30, “Charlie” – 22
Update the age of “Alice” to 26
Remove “Bob”
Key and Value Iteration:
Given a HashMap<String, String> representing a phone book, iterate over the map to print all names and their corresponding phone numbers.
Phone book: “John” – “555-1234”, “Alice” – “555-5678”, “Bob” – “555-8765”
Finding a Value by Key:
Write a method that takes a HashMap<Integer, String> and an integer key as input and returns the corresponding value. If the key does not exist, return “Key not found”.
Dictionary: 1 – “Math”, 2 – “Science”, 3 – “History”
Key to search: 2, 5
Group by Property:
Given a list of Student objects with properties name and grade, create a HashMap<Integer, List<Student>> to group students by their grade.
Students: “Sara” – Grade 10, “Tom” – Grade 11, “Lily” – Grade 10, “Jack” – Grade 11
Basic Operations with List:
Write a Java program to create an ArrayList<String> and perform basic operations such as adding, inserting, removing, and checking for the presence of elements.
Add values: “Apple”, “Banana”, “Cherry”
Insert “Orange” at position 1
Remove “Banana”
Check if “Cherry” is in the list
Finding Elements:
Write a method that takes an ArrayList<String> and a String as input and returns all the indices where the string appears in the list.
List: “apple”, “banana”, “apple”, “cherry”, “apple”
String to search: “apple”
Array to List Conversion and Operations:
Write a program that converts an array of integers to a List<Integer> and performs operations like reversing the list and finding the maximum and minimum values.
Array: 6, 12, 3, 9, 15, 1
Sorting a List:
Given a List<Integer>, write a method to sort the list in ascending and descending order.
List: 9, 3, 7, 1, 4
Course Video
YouTube Reference :
The training covers the Java Collections Framework, including its concepts, syntax, and practical applications.
Yes, it includes examples demonstrating how to use various collection classes like ArrayList
, HashSet
, and HashMap
.
Yes, exercises involve creating and manipulating different types of collections to understand their usage in various scenarios.
Yes, it’s designed for beginners with clear explanations and step-by-step examples.
A Java IDE like Eclipse, IntelliJ IDEA, or an online compiler will suffice.
Yes, it covers how collections provide efficient ways to store, retrieve, and manipulate groups of objects.
Yes, the training is self-paced and accessible online anytime.
Yes, it explains the distinctions and appropriate use cases for lists, sets, queues, and maps.
It typically takes a few hours to complete, depending on your learning pace.
Yes, this Java Collections training is completely free on Iqra Technology Academy’s website.