Coll 3 PDF Free
Coll 3 PDF Free
We have been using an array to store a group of objects. But arrays are of fixed size and
are difficult to use compared to collections. So we are gonna move into collections. The
basic collection is a list. Now let us try out basic ArrayList.
Create a class Main and in the main method get the usernames and store them in an
ArrayList. After getting all the names, just display them in the same order.
Note: All Texts in bold corresponds to the input and rest are output
Sample Input and Output 1:
Enter the username 1
John
Do you want to continue?(y/n)
y
Enter the username 2
Joe
Do you want to continue?(y/n)
n
The Names entered are:
John
Joe
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String args[]) throws Exception{
//write your code here
boolean result=false;
List<String> list = new ArrayList<String>();
int i=1;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("Enter the username " + i++);
String name = scanner.nextLine();
list.add(name);
System.out.println("Do you want to continue?(y/n)");
String diss = scanner.nextLine();
result=diss.equals("y");
}while(result);
Set Introduction
In the program let’s try using a Set. The property of Set is, it doesn't allow duplicate
elements and does not maintain order like a list. Understand it by going through and
completing the problem.
Write a program to get the username and store it in the set and display the unique
number of the username in the set.
Create a driver class called Main. In the Main method, obtain username input from the
user.
Import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
TreeMap()
To assist Event organizers, you need to develop a console application that shows the
number of tickets sold in a particular price category. Thus enabling them to increase or
decrease seats allocated for different price levels and thereby boosting ticket sales. The
list of booking details that contains customer and price details are given.
Use TreeMap with price as key and number of seats booked as value.
Create a driver class named Main. In the main method, obtain details and display the
price along with the number of tickets in increasing order of price.
Input Format:
The first line of the input corresponds to the number of events 'n'.
The next 'n' line of inputs corresponds to the event details in CSV format (Customer
Name, Ticket Price, No of Seats Booked).
Refer to Sample Input and Output for formatting specifications.
Output Format:
The output consists of the number of tickets booked for a particular ticket price in
increasing order of price.
Use ("%-15s %s\n","Ticket Price","Tickets Booked") for the format.
Refer to Sample Input and Output for formatting specifications.
map.put(price, (seat+seatBooked));
} else {
map.put(price, seatBooked);
}
}
System.out.println("Ticket Price Tickets Booked");
for(Map.Entry m:map.entrySet()){
System.out.printf("%-15s %s\n",m.getKey(),m.getValue());
}
}
}
Comparable Interface
Let's get in touch with the comparable interface. Given the list of Address details, sort
them based on Pincode. If two address has the same Pincode, then sort them based on
address line 1. This sorting will help us for segregating users based on Pincode when
certain details (City and state details) are unavailable.
The Address class implements the comparable interface. Compare pin code, If Pincode
is the same then compare with addressLine1.
Create a driver class named Main to test the above class. Obtain input from the console
and sort the user list.
Input Format:
The first line input corresponds to the number of users 'n'.
The next 'n' line of inputs corresponds to the user details in CSV
format(Username,AddressLine 1,AddressLine 2,PinCode).
Refer to sample input for formatting specifications.
Output Format:
The output consists of user details in the CSV format in sorted order. Print the output in
the main method.
Refer to sample output for formatting specifications.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args){
//fill code here
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number of users:");
//int num = Integer.parseInt(sc.nextLine());
int num = sc.nextInt();
sc.nextLine();
System.out.println("Enter user address in CSV(Username,AddressLine 1,AddressLine 2,PinCode)");
//Address userAddress = new Address();
ArrayList<Address> address = new ArrayList<Address>();
for (int i = 0; i < num; i++) {
if (pinCode == address.pinCode)
{
return (addressLine1.compareTo(address.addressLine1));
//return 0;
}
else if (pinCode > address.pinCode)
{
return 1;
}
else
{
return -1;
}
}
}
reverse() method
In the collection, sort() method sort the objects in the ascending order. Suppose if we
want to sort the list of objects in the descending order, we can use of reverse() method.
Write a program to implement the reverse() method along with sort() to sort the list of
User objects in the descending order.
Implement Comparable and sort the user objects based on name and reverse it by using
the reverse().
Create a driver class Main and using the main method get the details, create a map and
display the details.
Hint: Sort the user details based on the name of the user.
Input format:
The first line of input consists of number of users n.
The next n line of input consists of user details in the CSV format
(name,mobileNumber,userName,password).
Output format:
Display the name and the mobile number of the user in the reverse order.
Use "%-15s%-15s" to display details in tabular format.
Refer to sample input and output for other further details and format of the output.
return (this.name.compareTo(user.name));
@Override
public String toString() {
return String.format("%-15s%-15s",getName(),getMobileNumber());
}
}
------------------------------
import java.io.*;
import java.util.*;
}
Collections.sort(UserList);
Collections.reverse(UserList);
}
catch (Exception e){
}
finally {
System.out.println("The user details in reverse order:");
System.out.printf("%-15s%-15s\n","Name", "Mobile number");
for (User user: UserList){
System.out.println(user.toString());
}
}
}
}
Generic Classes
Create a generic class Item with a data. Write two methods set and get, to set a value to
the data variable and to get the value of the data variable respectively. From Main class
create two object for the class Item of types Integer and String.
private T t;
public T get() {
return t;
}
}
-------------------
import java.util.Scanner;
import java.io.*;
integerItem.set(sc.nextInt());
sc.nextLine();
}
}
Iterator class
It is time to explore some unique classes and methods in Collections. The Iterator class is
one such. You have created test data for Stall class with the name of stall starting with
prefix 'test', It's time to remove those objects. While iterating a collection through a for
loop or a for each loop, you cannot modify or remove an element. The Iterator
class facilitates such functionalities. Hence while you iterate through a Collection using
Iterator you can modify the elements. Let's implement it to delete test data.
Create a driver class called Main. In the Main method, obtain stall input from the user
and create a list of Stall details. Using the Iterator class iterate through the List and
remove stalls with a name starting with 'test'.
Display the list of details in tabular form.
Input format:
The first line consists of the number of stalls 'n'
The next 'n' line consists of 'n' stall details given in CSV format. (name,
detail,type,ownerName)
Output format:
The first line of output displays the heading of the stall details.
Then the stall details without containing the prefix 'test' are displayed in tabular format
Use ("%-15s %-20s %-15s %s") for formatting
Refer to the sample Input and Output for further details and for the formatting
specifications.
Write a program to take hall objects as input in the list and sort them in the order of
their costPerDay using sort() method of the comparable interface. Then display them in
tabular form.
Override toString() and print the details in a tabular format. And implement comparable
interface in the class.
Create driver class Main and use the main method to get inputs, sort, and display.
Input Format:
The first line has the number of halls n.
The next n lines have details of the hall in CSV
format. (name,contactNumber,costPerDay,ownerName).
Output format:
Use "%-15s%-15s%-15s%-15s" to display the hall details in the sorted order based on
the cost per day as in tabular form.
Refer to sample input and output for other further details and format of the output.
Note: All Texts in bold corresponds to the input and rest are output.
Seat Arrangement
Having recapped with already learned collection concepts, it's time to get involved in
complex collection concepts. We would have created a list of primitive datatype and
objects. Let's start with List of List in this exercise. Create a structure of seats in a
StageEvent given the details of the number of rows and columns. Assign Section
chronologically starting with 'A' and number starting from 1.
Strictly adhere to the Object-Oriented specifications given in the problem statement.
All class names, attribute names, and method names should be the same as specified in
the problem statement.
Create a driver class called Main. In the Main method, obtain input from the user and
create a list of list of Seats. obtain Seat details for booking and at last display the
Booked seats.
Input format:
The first line corresponds to the number of rows
The second line corresponds to the number of seats per row
The third line consists of tickets to be booked in CSV format.
Output format:
Seats that are booked are represented by "--" whereas the unbooked seats are
represented by the section and number
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output 1:
Email Search
In your application let’s dive deep into Set and explore its inbuilt functions. In this
problem experiment with containsAll() method. Write a program to search all the email
addresses which are given as CSV format.
Create a Main class. Obtain email addresses from the user and add them to a Set. At last,
get a String that has multiple email addresses in CSV format. Print "Email addresses are
present" if all email addresses are present in the Set, else print "Email addresses are not
present".
Note: All Texts in bold corresponds to the input and rest are output
List of List
We have already seen a problem in the list of lists. So let's try to use it in our application.
While the users try to book the tickets for the events they should know the count of
remaining tickets. Let's create a list of 5 days of the week each has a list of the count of
remaining tickets for 4 shows. List<List<Integer>> is the general format and for
the problem, dayList<showList<count>>, ie., store the count of ticket available for each
show of a day in a list and then place these lists for each day of a week inside another
list.
The maximum number of tickets for a show is 100. So after getting the bulk booked
tickets from the user, subtract and store the remaining count of tickets for the whole
week in this list of lists.
Create a driver class Main and use the main method to get the count of already booked
tickets and create a list of the list to store the remaining count.
Note:CSV input format is (show1,show2,show3,show4) for each day. And enter day to
know remaining ticket count for the day.
Refer sample input/output for other further details and format of the output.
Input Format:
The first five lines have the number of tickets booked in each day
The next lines have the day in which the remaining ticket to be shown
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:
Create a class TicketBooking with following private attributes which implements the
Comparable interface
Attributes Datatype
customerName String
price Integer
Include appropriate getters and setters
Create default constructor and a parameterized constructor with arguments in
order TicketBooking(String customerName, Integer price) and overrides the compare
method.
Create a driver class named Main to test the above class. Obtain input from the console ,
get a list of TicketBooking, and use Collections.min() and Collections.max() to find the
customer who spent more and less amount for ticket booking.
Input Format:
The first line input corresponds to the number of customers 'n'. n>0 else display "Invalid
Input".
The next 'n' line of inputs corresponds to the user details in CSV format (Customer
Name, Price).
Refer to sample input for formatting specifications.
Output Format:
The output consists of the minimum and maximum amount spent by the customer. If
two or more customer price is the same, keep the 1st one's price.
Refer to sample output for formatting specifications.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output-1:
Enter the number of customers
4
Enter the booking price accordingly with customer name in CSV(Customer Name,Price)
Jenny,1200
Maria,450
Jaquilin,600
Renita sarah,150
Renita sarah spends minimum amount of Rs.150
Jenny spends maximum amount of Rs.1200
Replica of a List
User data is always important and backup has to be made for every now and then. First
of all, we'll back up the User authorization data for practice. The List of user details is
provided. create a replica of the given list and store it in a backup list. An exact replica of
a collection can be created using the copy() method of the List API.
Follow the instruction below and display the backup list.
Create a driver class named Main to test the above class. In Main class create
destination list of size as same source list with null values(without a null list it
throws IndexOutOfBoundsException) and this has sent as destination list to the backUp
method.
Input Format:
The first line input corresponds to the number of users 'n'. n>0 else display "Invalid
Input".
The next 'n' line of inputs corresponds to the user details in CSV format(Username,
Password).
Refer to sample input for formatting specifications.
Output Format:
The output consists user details in the format of System.out.format("%-20s
%s\n","Username","Password");.
Refer sample output for formatting specifications.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output-1:
Enter number of users
3
Enter the user details in CSV(Username,password)
Daniel,merry
Bisoph,qwertyuio!@12345
Jaques,877878785565
Copy of user list:
Username Password
Daniel merry
Bisoph qwertyuio!@12345
Jaques 877878785565
State map
Let's have a different variant of multimap. Create a
Map<String,Map<String,List<Address>>> with State name as key and a map as a value
having City name as key and List of address as value. It should be understood that the
address should have the state and city name as that of the key. At last obtain state and
city as search terms and display the corresponding list of addresses.
Attributes Datatype
addressLine1 String
addressLine2 String
city String
state String
pincode Integer
Create a driver class called Main. In the main method, obtain address details and create
the map of above specification. Obtain state and city as search term and display the
address that has the given city and state. If no such address is present, Print "Searched
city not found" or "Searched state not found" accordingly.
Note:
[Strictly adhere to the Object-Oriented Specifications given in the problem statement.
All class names, attribute names and method names should be the same as specified in
the problem statement.]
Input format:
Output format:
Address details are displayed in tabular format (Use "%-15s %-15s %-15s %-15s %s\n"
for formatting Address details.)
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output 1:
Generic Methods
Write a single generic method declaration that can be called with arguments of different
types to print the elements of Integer, Double and Character arrays.