You are on page 1of 13

SHRUTI GARG 19BCE0994

Fall Semester 2020-21


CSE1007 – Java Programming Lab

NAME: SHRUTI GARG REG NO.:19BCE0994

SLOT: L19+L20 DATE: 18/04/2021

Practice Problems on Collections

1. Write a program to demonstrate the knowledge of students in working with Java collection
framework.
Eg., Assume only a maximum of 3 courses can be registered by a student for week end
semester classes. Create a hashmap ‘h1’ with ‘n’ key-value pairs where keys are the names
of students and values are the courses registered by them. Create another hashmap ‘h2’ with
‘m’key-value pairs where keys are the names of courses offered for B.Tech-IT and values
are the names of faculty handling the courses. Write appropriate code to
- Add or remove a student from h1
- Iterate over the maps and display the key-value pairs stored in them
- Given a student name, fetch the names of all those who teach him/her.
Eg:, if the elements of h1 are

Stud Courses registered


name
A Python, maths, c
B c, c++
C C++, physics,chemistry

And if the elements of h2 are


Course name Faculty
Python 111
Maths 222
C 333
C++ 444
Physics 555
Chemistry 666
Digital 777
electronics
SHRUTI GARG 19BCE0994

For the student “B”, faculty should be displayed as 333 and 444.

CODE:
package cyclesheet3;
import java.util.*;

public class Q1 {

public static void main(String[] args) {

System.out.println("Shruti Garg");
System.out.println("19BCE0994\n");

HashMap<String, List<String>> h1 = new LinkedHashMap<>();


HashMap<String, String> h2 = new LinkedHashMap<>();

List<String> subjects = Arrays.asList("Python", "Math", "C");


System.out.println("Students A,B,C added\n");
h1.put("A",subjects);
subjects = Arrays.asList("C","C++");
h1.put("B",subjects);
subjects = Arrays.asList("C++","Physics","Chemistry");
h1.put("C",subjects);

h2.put("Python","111");
h2.put("Math","222");
h2.put("C","333");
h2.put("C++","444");

for(Map.Entry m:h1.entrySet()){
System.out.print(m.getKey()+" :");
subjects = (List<String>)m.getValue();
for(String s:subjects)
System.out.print(s + " ");
System.out.println();
}
System.out.println();

for(Map.Entry m:h2.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
SHRUTI GARG 19BCE0994

Scanner sc = new Scanner(System.in);


System.out.println("\nEnter a student: ");
String a = sc.nextLine();

System.out.println("\nFaculties for "+a+" are : ");


for(Map.Entry m:h1.entrySet()){
if(m.getKey().equals(a)){
for(Map.Entry m2:h2.entrySet()){
subjects = (List<String>)m.getValue();
if(subjects.contains(m2.getKey()))
System.out.println(m2.getValue());
}
}
}
}
}

OUTPUT:
SHRUTI GARG 19BCE0994

2. Create a class tourist which has the data members name, state, famous_spot . Create a list of
all the states in the south. Add the tourist places to the list based on state. Display the list in
sorted order. Search a tourist spot from the list and display the details. Raise an exception if
the details are not present.

CODE:

package cyclesheet3;
import java.util.*;

class tourist
{
String name,state,famous_spot;
tourist(String name,String state,String fspot)
{
this.name = name;
this.state = state;
this.famous_spot = fspot;
}

}
class SortByState implements Comparator<tourist>
{
@Override
public int compare(tourist a, tourist b) {
return a.state.compareTo(b.state);
}
}
class NotFoundSpot extends Exception
{
public NotFoundSpot(String s)
{
super(s);
}
}
public class Q2 {

public static void main(String args[]) throws NotFoundSpot


{
System.out.println("\nShruti Garg");
System.out.println("19BCE0994\n");

List<tourist> list = new ArrayList<tourist>();


tourist t1 = new tourist("Mysore","Karnataka","Mysore
Fort");
SHRUTI GARG 19BCE0994

tourist t2= new tourist("Kochi","Kerela","Kochi");


tourist t3 = new tourist("Vellore","Tamil Nadu","Golden
Temple");
tourist t4 = new tourist("Hyderabad","Andhra
Pradesh","Charminar");

list.add(t1);
list.add(t2);
list.add(t3);
list.add(t4);

System.out.println("Famous Spots:");
Collections.sort(list, new SortByState());
for(tourist str: list)
{

System.out.println(str.famous_spot);
}

System.out.println();
Scanner sc= new Scanner(System.in);
System.out.println("Enter the tourist spot: ");
String spot = sc.nextLine();

int c=0;
Iterator ai = list.iterator();
while(ai.hasNext())
{
tourist temp = (tourist)ai.next();
if(spot.equalsIgnoreCase(temp.famous_spot))
{
System.out.println("Found: "+temp.famous_spot);
System.out.println("City: "+temp.name);
System.out.println("State: "+temp.state);
c=1;
}
}
if(c==0)
{
throw new NotFoundSpot(spot+" not found in list");
}
}
}
SHRUTI GARG 19BCE0994

OUTPUT:
SHRUTI GARG 19BCE0994

3. The following list gives the amount of rainfall (in cms) recorded at a particular place for 12
months.
10.2, 11.9, 8.0, 11.2, 10.8, 6.9, 8.2, 11.5, 10.4, 8.7, 7.8, 7.5.
Store these values in a queue. Find the average rainfall and display the count of the number
of months in which the rainfall is more than the average.

CODE:

package cyclesheet3;
import java.util.*;

public class Q3 {

public static void main(String args[])


{
System.out.println("\nShruti Garg");
System.out.println("19BCE0994\n");

Scanner sc = new Scanner(System.in);


Queue<Float> q= new PriorityQueue<>();
int i=0,c=0;
float s=0;

System.out.println("Enter amount of rainfall for 12 Months: ");


while(i!=12)
{
q.add(sc.nextFloat());
i++;
}
Iterator<Float> it = q.iterator();
while(it.hasNext())
{
s+=(Float)it.next();
}
System.out.println("\nAverage rainfall: "+(s/12.0));

Iterator<Float> it2 = q.iterator();


while(it2.hasNext())
{
if(((Float)it2.next())>(s/12.0))
{
c++;
}
}
System.out.println("\nCount of Months with more than avg
rainfall: "+c);
}
}
SHRUTI GARG 19BCE0994

OUTPUT:

4. The librarian would like to maintain a list which has the information about the book name,
author, price, no_of_copies in the library. Max 5 books can be placed in a rack. Create a
hashmap of the book object with the rack no. Write a method search to read a book name
and return its rack no. Write a method sort to display the book name in a particular rack.

CODE:
package cyclesheet3;
import java.util.*;

class book{
String name;
String author;
int price;
int no_of_copies;
book(String name, String author, int price, int no_of_copies){
this.name = name;
this.author = author;
this.price = price;
this.no_of_copies = no_of_copies;
}
}
public class Q4 {

public static int search(HashMap<book,Integer> list, String bname){


for(Map.Entry<book, Integer> entry:list.entrySet()){
book b=entry.getKey();
SHRUTI GARG 19BCE0994

if(b.name.equals(bname)){
return entry.getValue();
}
}
return -1;
}
public static void sort(HashMap<book,Integer> list, int rack){
for(Map.Entry<book, Integer> entry:list.entrySet()){
if(rack==entry.getValue()){

book b = entry.getKey();
System.out.println("Book details: ");
System.out.println("Book Name: " + b.name);
System.out.println("Book Author: " + b.author);
System.out.println("Price: " + b.price);
System.out.println("No. of Copies: " +
b.no_of_copies+"\n");
}
}
}
public static void main(String[] args){

System.out.println("\nShruti Garg");
System.out.println("19BCE0994\n");

Scanner sc = new Scanner(System.in);


HashMap<book,Integer> list = new HashMap();
book[] objs = new book[5];

objs[0] = new book("Hunger_Games", "Jeff", 190, 10);


objs[1] = new book("Harry_Potter", "Jk Rowling", 340, 90);
objs[2] = new book("Alchemist", "Paul", 172, 40);
objs[3] = new book("Fantasy_land", "George", 250, 50);
objs[4] = new book("Haunted_Tales", "Jeff", 782, 20);

for (int i = 0; i < 5; i++)


list.put(objs[i],(i+1));

boolean flag = true;


int choice;
while(flag){
int rack;
String s;
System.out.println("1)Search Rack No. given the Book name\n"
+
"2)Search Book name given the Rack No.\n" +
"3)Exit");
System.out.print("\nChoose an option: ");
choice = sc.nextInt();
switch (choice){
SHRUTI GARG 19BCE0994

case 1:
System.out.print("Enter the Book name: ");
s = sc.next();
rack = search(list, s);
System.out.println("The Rack Number is: "+rack+"\n");
break;
case 2:
System.out.print("Enter the Rack No: ");
rack = sc.nextInt();
sort(list, rack);
break;
case 3:
flag = false;
break;
}
}
}
}

OUTPUT:
SHRUTI GARG 19BCE0994

5. An Industry collects the product sample measurements (product id, diameter, length,
weight) for quality test and sends it to the quality assurance (QA) department in a serialized
manner. The QA departments deserialize the samples and checks if the length=10cm,
diameter=3cm, weight=100gms. The product id of defective samples is stored in a set. The
product id of correct samples is stored in another sort. Sort the correct samples in list.

CODE:

package cyclesheet3;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

class Sample implements Serializable


{
public String pid;
public int diameter;
public int length;
public int weight;
// Default constructor
public Sample(String pid, int diameter, int length, int weight)
{
this.pid = pid;
this.diameter = diameter;
this.length = length;
this.weight = weight;
}
}

public class Q5 {

public static void main(String[] args)


{
System.out.println("\nShruti Garg");
System.out.println("19BCE0994\n");

Scanner scanner = new Scanner(System.in);


String pid;
int diameter;
int length;
int weight;
ArrayList<String> list = new ArrayList<>();
int i = 0;
int n;
System.out.println("Enter the number of Product samples: ");
n = scanner.nextInt();
for(int l=0; l<n; l++)
{
SHRUTI GARG 19BCE0994

System.out.println("\nEnter the details of product: "+(l+1));


System.out.print("P_ID: ");pid = scanner.next();
System.out.print("Length: ");length = scanner.nextInt();
System.out.print("Diameter: ");diameter = scanner.nextInt();
System.out.print("Weight: ");weight = scanner.nextInt();
Sample object = new Sample(pid, diameter, length, weight);
String filename = "file.txt"; // Serialization
try
{
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
}
catch (IOException ex)
{
System.out.println("IOException is caught");
}
Sample object2 = null;
try {
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
object2 = (Sample) in.readObject(); in.close();
file.close();
if (object2.length != 10 || object2.diameter != 3 ||
object2.weight != 100)
{
list.add((object2.pid).toString());
}
}
catch (IOException ex)
{
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
System.out.println("The product id of defective sample is:");
for(String j:list)
{
System.out.println(j);
}
}
}
SHRUTI GARG 19BCE0994

OUTPUT:

You might also like