Final Practice question[1]
Final Practice question[1]
Sample Input/Output:
ArrayList: [10, 20, 30, 40, 50]
After removing element at index 2: [10, 20, 40, 50]
Contains 20? True
Solution:
System.out.println("ArrayList using index:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println("ArrayList using enhanced for-loop:");
for (int num : list) {
System.out.print(num + " ");
}
System.out.println();
list.remove(2);
System.out.println("After removing element at index 2: " + list);
Sample Input/Output:
Input: [5, 9, 12, 7, 3]
Output: Maximum element: 12
int ma = Collections.max(list);
System.out.println(ma);
3. Remove Duplicates from an ArrayList
Sample Input/Output:
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Sample Input/Output:
Input: list1 = [1, 2, 3], list2 = [4, 5, 6]
Output: Merged list: [1, 2, 3, 4, 5, 6]
list.addAll(list2);
System.out.println("Merged List: " +list);
5. ArrayList Sorting
Sample Input/Output:
Input: [4, 1, 7, 2, 9]
Output (ascending): [1, 2, 4, 7, 9]
Output (descending): [9, 7, 4, 2, 1]
// Ascending order
// Collections.sort(list);
// System.out.println("Ascending: " + list);
//
// // Descending order
// Collections.sort(list, Collections.reverseOrder());
// System.out.println("Descending: " + list);
6. Find Common Elements Between Two ArrayLists
Problem: Write a Java program to find the common elements between two
ArrayLists of strings.
Sample Input/Output:
Input: list1 = ["apple", "banana", "orange"], list2 = ["banana", "kiwi",
"orange"]
Output: Common elements: [banana, orange]
list.retainAll(list2);
7. Reverse an ArrayList
Sample Input/Output:
Input: [10, 20, 30, 40]
Output: [40, 30, 20, 10]
Collections.reverse(list);
Sample Input/Output:
Input: []
Output: Is the ArrayList empty? true
Sample Input/Output:
Input: [10, 20, 30, 40]
Insert 25 at index 2
Output: [10, 20, 25, 30, 40]
list.add(2, 25);
Problem: Write a Java program to remove all elements from an ArrayList that
are divisible by 3.
Sample Input/Output:
Input: [3, 5, 9, 12, 14, 18]
Output: [5, 14]
Sample Input/Output:
Input: [1, 2, 3, 4, 5]
Output (shuffled): [4, 2, 5, 1, 3]
Collections.shuffle(list);
Sample Input/Output:
Input: [1, 2, 3, 4]
Output: [1, 2, 3, 4]
Integer[] array = {1, 2, 3, 4}; ArrayList<Integer> list = new
ArrayList<>(Arrays.asList(array));
14. Find the Index of a Specific Element
Sample Input/Output:
Input: [10, 20, 30, 40], element = 30
Output: Index of 30: 2
Sample Input/Output:
Input: [1, 2, 2, 3, 4, 2]
Remove all occurrences of 2
Output: [1, 3, 4]
list.removeIf(num -> num == n);
System.out.println("Updated ArrayList: " + list);
Sample Input/Output:
Input: [10, 20, 30, 20, 40], replace 20 with 50
Output: [10, 50, 30, 50, 40]
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 20) {
list.set(i, 50);
} }
Sample Input/Output:
Input: [1, 3, 4, 5, 2]
Output: Second largest element: 4
Collections.sort(list);
System.out.println("Second largest element: " +list.get(list.size()-2));
Problem: Write a Java program to check if two ArrayLists are equal. Two
ArrayLists are equal if they contain the same elements in the same order.
Sample Input/Output:
Input: list1 = [1, 2, 3], list2 = [1, 2, 3]
Output: Are they equal? True
list1.equals(list2)
Sample Input/Output:
Input: [1, 2, 3, 4]
Copied ArrayList: [1, 2, 3, 4]
Problem: Create a custom Student class with fields name and age. Write a Java
program to:
Sample Input/Output:
Input: [Student(name=John, age=20), Student(name=Mary, age=17),
Student(name=Tom, age=19)]
Output: John, Tom
title (String)
author (String)
price (double)
Write a program to:
Sample Input/Output:
name (String)
department (String)
salary (double)
Sample Input/Output:
Department: IT
Employees in IT: [John, Alice]
id (int)
name (String)
marks (double)
Sample Input/Output:
productId (int)
productName (String)
price (double)
quantity (int)
Sample Input/Output:
Product ID: 101, Name: "Laptop", Quantity: 10, Total Value: 450000.0
memberId (int)
memberName (String)
booksBorrowed (ArrayList<Book>)
Sample Input/Output:
reservationId (int)
customerName (String)
roomNumber (int)
checkInDate (String)
checkOutDate (String)
Sample Input/Output:
Reservation ID: 1, Customer: "John", Room: 101, Check-in: 2024-10-01, Check-out: 2024-
10-05
carId (int)
model (String)
brand (String)
isAvailable (boolean)
Sample Input/Output:
eventId (int)
eventName (String)
eventDate (String)
attendees (ArrayList<String>)
Sample Input/Output:
ticketId (int)
passengerName (String)
trainNumber (int)
seatNumber (String)
isConfirmed (boolean)
Sample Input/Output:
courseId (int)
courseName (String)
studentsEnrolled (ArrayList<Student>)
Sample Input/Output:
1. Managing a Library
A library needs to manage a list of books. Each book is identified by its title, and new books are added as
they are acquired. The library also allows for removing books no longer available. The librarian needs to:
Question: Write a Java program using the List interface to implement the above requirements. Which
implementation (ArrayList or LinkedList) is more suitable, and why?
2. Employee Attendance System
In a company, employees mark their attendance each day. The attendance system stores employee IDs in the
order they mark attendance.
At the end of the day, the manager wants to view all the marked IDs.
A duplicate entry of an employee ID may occur, which needs to be removed without disturbing the order.
Question: Write a program to store and process employee IDs using the List interface. How would you
ensure no duplicates exist in the list?
3. Playlist Manager
Question: Design a Java class using the List interface to represent a playlist. How would you efficiently
reorder songs using an ArrayList?
In a classroom, a teacher maintains a roll call list in the order students arrive. The teacher wants to:
Question: Write a Java program using the List interface to manage the roll call list. Discuss whether
ArrayList or LinkedList is better for frequent additions and removals.
5. Shopping Cart
An e-commerce platform uses a shopping cart feature to store items that customers want to purchase. The
cart:
Question: Implement the shopping cart functionality using the List interface. Explain how the get() method
helps in retrieving an item at a specific index.
An airport tracks the order in which passengers check in for a flight. The list of passengers:
A university announces exam results for students in alphabetical order of their names. The result-processing
system:
Question: Using the List interface, write a program to add and sort student names. How would you sort the
list, and which List implementation is more efficient for this purpose?
A movie theater tracks seat bookings in rows. Each row is represented by a list of booked seat numbers. The
system:
Question: Write a Java program using the List interface to manage seat bookings for one row. Discuss
whether LinkedList is a good choice if bookings and cancellations are frequent.
9. Tournament Rankings
Question: Implement a program using the List interface to manage rankings. Explain how inserting elements
at a specific position affects the performance of ArrayList versus LinkedList.
Question: Write a Java program using the List interface to manage the inventory. How does the choice of
List implementation affect retrieval and update operations?
SET
Unique Library Books
Story: You are managing a library system where every book has a
unique ISBN number. However, users sometimes try to add duplicate
ISBNs mistakenly.
Question:
Write a Java program using a Set to store unique ISBNs of books. If a
duplicate ISBN is attempted to be added, notify the user.
2. Team Formation
Question:
Use a Set to store player names, ensuring no duplicate names exist in the
final team list. Simulate this process by inputting player names into your
program.
Question:
Write a program that uses a Set to maintain the guest list. Add sample
entries, including duplicates, and display the final unique guest list.
Question:
Simulate this functionality using a Set. Write a program to store
followers of a user and demonstrate how duplicates are handled.
Question:
Write a program to store product codes in a Set. Show how the Set
prevents duplicate entries, and display the final list of unique codes.
Question:
Implement a program using a Set to store badge IDs. Demonstrate
adding valid and duplicate IDs, and print the final unique list.
Question:
Write a program using a Set to find and print duplicate words from a
given paragraph of text.
8. Classroom Attendance
Story: A school maintains attendance for each class. Each student's roll
number must be unique.
Question:
Simulate the attendance system using a Set to store roll numbers. Write
a program to add, check for duplicates, and print the final attendance list.
9. Music Playlist
Story: A music app allows users to create playlists. Songs must not be
repeated in a playlist.
Question:
Write a program using a Set to manage a playlist. Demonstrate adding
duplicate songs and show how they are handled.
Question:
Create a Java program using a Set to store voter IDs. Demonstrate
adding duplicate IDs and ensure the system only keeps unique IDs.
MAP/HASHMAP
Sample Input/Output:
Student: Alice, Grade: 85
Student: Bob, Grade: 90
Student: Charlie, Grade: 75
...
Enter student name to retrieve grade: Bob
Bob's grade is: 90
2. Frequency of Characters
Problem: Write a Java program that takes a string as input and uses a HashMap to
count the frequency of each character in the string. Ignore spaces.
Sample Input/Output:
Input: "hello world"
Output: {h=1, e=1, l=3, o=2, w=1, r=1, d=1}
Problem: Given an array of integers, use a HashMap to find and print the duplicate
elements.
Sample Input/Output:
Input: [1, 2, 3, 1, 4, 5, 2]
Output: [1, 2]
Problem: Write a Java program that reads a sentence and uses a HashMap to count
the occurrences of each word in the sentence. Ignore case sensitivity.
Sample Input/Output:
Input: "Java is fun and Java is powerful"
Output: {java=2, is=2, fun=1, and=1, powerful=1}
5. Anagram Checker
Problem: Write a program to check whether two strings are anagrams of each
other using a HashMap. Two strings are anagrams if they contain the same
characters with the same frequency.
Sample Input/Output:
Input: "listen", "silent"
Output: true
Problem: Given a list of words, group them based on whether they contain the
same set of letters. Use a HashMap where the key is the sorted version of the word,
and the value is a list of words with the same letters.
Sample Input/Output:
Input: ["bat", "tab", "rat", "tar", "art"]
Output: {abt=[bat, tab], art=[rat, tar, art]}
Problem: Given an array of integers and a window size k, use a HashMap to print
the count of distinct elements in every window of size k.
Sample Input/Output:
Input: arr = [1, 2, 1, 3, 4, 2, 3], k = 4
Output: [3, 4, 4, 3]
Explanation:
Window [1, 2, 1, 3] has 3 distinct numbers.
Window [2, 1, 3, 4] has 4 distinct numbers.
...
Problem: Given an array of integers and a target sum, use a HashMap to find if
there are two numbers in the array that sum up to the target. Return the indices of
those numbers.
Sample Input/Output:
Input: arr = [2, 7, 11, 15], target = 9
Output: [0, 1] (since arr[0] + arr[1] = 2 + 7 = 9)
Problem: Write a Java program to store employee names and their departments
using a HashMap. Implement the following functionalities:
Add a new employee and their department.
Get the department of a specific employee.
List all employees in a given department.
Sample Input/Output:
Input: Add Alice in HR, Bob in IT, Eve in IT
Output: Employees in IT: [Bob, Eve]
Problem: Implement a student ranking system where students and their scores
are stored in a HashMap. Write a function to:
Sample Input/Output:
Input: Alice - 85, Bob - 90, Charlie - 75
Output: Bob: 1st, Alice: 2nd, Charlie: 3rd
Problem: Write a Java program to find the intersection of two arrays using a
HashMap. The result should contain all the common elements between the two
arrays.
Sample Input/Output:
Input: arr1 = [1, 2, 2, 3], arr2 = [2, 2, 4, 5]
Output: [2, 2]
Sample Input/Output:
Input: {Alice=85, Bob=90, Charlie=75}
Output: {Charlie=75, Alice=85, Bob=90} // sorted by value
Sample Input/Output:
Input: map1 = {Alice=85, Bob=90}, map2 = {Alice=85, Bob=90}
Output: true
Problem: Write a Java program to merge two HashMap instances into a new one.
If there are any duplicate keys, combine their values (e.g., concatenate strings or
sum integers).
Sample Input/Output:
Input: map1 = {Alice=85, Bob=90}, map2 = {Bob=10, Charlie=75}
Output: {Alice=85, Bob=100, Charlie=75}
Sample Input/Output:
Input: arr = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2] (1 appears 3 times, 2 appears 2 times)
These questions cover the core functionalities of Java's HashMap and help in
developing both theoretical and practical knowledge about its use cases.
import java.util.HashMap;
AnagramChecker
public class AnagramChecker {
// Function to check if two strings are anagrams
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert both strings to lowercase for case-insensitivity
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
return true;
}
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
if (areAnagrams(str3, str4)) {
System.out.println(str3 + " and " + str4 + " are anagrams.");
} else {
System.out.println(str3 + " and " + str4 + " are not anagrams.");
}
}
}
import java.util.*;
import java.util.*;
return result;
}