Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
101 views

Java Collection & Multithreading Program

The document discusses several examples of using different Java collection classes like ArrayList, LinkedList, TreeSet, HashMap. It includes examples to add, remove and display elements from these collections. It also discusses examples involving file reading and GUI based collection operations.

Uploaded by

surajthorat810
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Java Collection & Multithreading Program

The document discusses several examples of using different Java collection classes like ArrayList, LinkedList, TreeSet, HashMap. It includes examples to add, remove and display elements from these collections. It also discusses examples involving file reading and GUI based collection operations.

Uploaded by

surajthorat810
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

collection

SET A
1) Write a java program to accept names of ‘n’ cities, insert same into array list collection
and display the contents of same array list, also remove all these elements

import java.util.Scanner;
import java.util.*;
public class city
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList al=new ArrayList();
System.out.println("enter how many cities:");
int n=sc.nextInt();
System.out.println("enter the cities:");
sc.nextLine();
for(int i=0;i<n;i++)
{
String cities=sc.nextLine();
al.add(cities);
}
System.out.println("cities"+al);
System.out.println("ArrayList after removing the element:");
al.clear();
System.out.println("cities"+al);
sc.close();
}
}
/***************output******************
bcs@localhost:~/Desktop/TY2sem/java/assi1> javac city.java
bcs@localhost:~/Desktop/TY2sem/java/assi1> export
CLASSPATH=$CLASSPATH:/home/bcs/Desktop/TY2sem/java/assi1/p.jar
bcs@localhost:~/Desktop/TY2sem/java/assi1> java city
enter how many cities:
4
enter the cities:
sangmner
nagar
nimaj
gunjalwadi
cities[sangmner, nagar, nimaj, gunjalwadi]
ArrayList after removing the element:
cities[]
*/

2) Write a java program to read ‘n’ names of your friends, store it into linked list,
also display contents of the same.

import java.util.Scanner;
import java.util.*;
public class friend
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
LinkedList l1=new LinkedList();
System.out.println("enter how many friends:");
int n=sc.nextInt();
System.out.println("enter the "+n+"friends:");
sc.nextLine();
for(int i=0;i<n;i++)
{
String name=sc.nextLine();
l1.add(name);
}
System.out.println("friend"+l1);
sc.close();
}
}
/********************Out Put****************
bcs@localhost:~/Desktop/TY2sem/java/assi1> javac friend.java
bcs@localhost:~/Desktop/TY2sem/java/assi1> export
CLASSPATH=$CLASSPATH:/home/bcs/Desktop/TY2sem/java/assi1/p.jar
bcs@localhost:~/Desktop/TY2sem/java/assi1> java friend
enter how many friends:
4
enter the 4friends:
ram
sham
sanjay
vijay
friend[ram, sham, sanjay, vijay]
*/

3) Write a program to create a new tree set, add some colors (string) and print out
the tree set.

import java.util.Scanner;
import java.util.*;
public class tree
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
TreeSet ts=new TreeSet();
System.out.println("enter how many color:");
int n=sc.nextInt();
System.out.println("enter the color:");
sc.nextLine();
for(int i=0;i<n;i++)
{
String color=sc.nextLine();
ts.add(color);
}
System.out.println(ts);
sc.close();
}
}
/**********************Out Put*****************
bcs@localhost:~/Desktop/TY2sem/java/assi1> javac tree.java
bcs@localhost:~/Desktop/TY2sem/java/assi1> export
CLASSPATH=$CLASSPATH:/home/bcs/Desktop/TY2sem/java/assi1/p.jar
bcs@localhost:~/Desktop/TY2sem/java/assi1> java tree
enter how many color:
5
enter the color:
red
white
green
pink
blue
[blue, green, pink, red, white]
*/

4) Create the hash table that will maintain the mobile number and student name. Display
the contact list.

import java.util.*;
import java.util.Scanner;
class student
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
Hashtable hs=new Hashtable();
System.out.println("enter how many records:");
int n=input.nextInt();
System.out.println("enter records:");
input.nextLine();
for(int i=0;i<n;i++)
{
System.out.println("enter mobile number:");
Integer mno=input.nextInt();
System.out.println("enter stud name:");
String snm=input.next();
hs.put(snm,mno);
}
System.out.println("names of color:"+hs);
System.out.println("size of friends:"+hs.size());
input.close();
}
}

SET B
1) Accept ‘n’ integers from the user. Store and display integers in sorted order having
proper collection class. The collection should not accept duplicate elements.

import java.util.Scanner;
import java.util.*;
public class setb1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
TreeSet ts=new TreeSet();
System.out.println("enter how many Integer:");
int n=sc.nextInt();
System.out.println("enter Integer:");
for(int i=0;i<n;i++)
{
String Integer=sc.nextLine();
ts.add(Integer);
}
System.out.println("integer in sorted order and without the duplicate value"+ts);
sc.close();
}
}
/**************************Out put********************
bcs@localhost:~/Desktop/TY2sem/java/assi1/setb> javac setb1.java
bcs@localhost:~/Desktop/TY2sem/java/assi1/setb> export
CLASSPATH=$CLASSPATH:/home/bcs/Desktop/TY2sem/java/assi1/p.jar
bcs@localhost:~/Desktop/TY2sem/java/assi1/setb> java setb1
enter how many Integer:
6
enter Integer:
1
2
3
4
1
integer in sorted order and without the duplicate value[, 1, 2, 3, 4]*/

2) Write a program to sort HashMap by keys and display the details before sorting
and after sorting

import java.util.Scanner;
import java.util.*;
class setb2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
HashMap hm=new HashMap();
System.out.println("enter how many number:");
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("enter no:");
Integer no=sc.nextInt();
System.out.println("enter name:");
String name=sc.nextLine();
hm.put(no,name);
}
System.out.println("before sorting :"+hm);
TreeMap tm=new TreeMap(hm);
System.out.println("after sorting :"+tm);
}
}
/****************output***************
bcs@localhost:~/Desktop/TY2sem/java/assi1/setb> javac setb2.java
bcs@localhost:~/Desktop/TY2sem/java/assi1/setb> java setb2
enter how many number:
2
enter no:
1
enter name:
enter no:
2
enter name:
before sorting :{1=, 2=}
after sorting :{1=, 2=}
*/

3) Write a program that loads names and phone numbers from a text file where the data
is organized as one line per record and each field in a record are separated by a tab
(\t).it takes a name or phone number as input and prints the corresponding other
value from the hash table (hint: use hash tables)

import java.io.*;
import java.util.*;
public class setb3{
public static void main(String args[]){
try{
String name=" ";
String phno=" ";
Hashtable ht=new Hashtable();
File f=new File("C.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String st;
while((st=br.readLine())!=null){
name=st.substring(0,st.indexOf("\t"));
phno=st.substring(st.indexOf("\t")+1);
ht.put(name,phno);
System.out.println(st);
}

}
catch(Exception e){
System.out.println(e);
}
}
}

SET C
1) Create a java application to store city names and their STD codes using an
appropriate collection. The GUI should allow the following operations:
i. Add a new city and its code (No duplicates)
ii. Remove a city from the collection
iii. Search for a city name and display the code

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class demo extends JFrame implements ActionListener{
Scanner input=new Scanner(System.in);

Hashtable<String,String> hash=new Hashtable<String,String>();


JLabel lbl1,lbl2;
JButton add,remove,search;
JTextField txt1,txt2;
demo()
{
setTitle("CITY");
setSize(800,600);
setLayout(new GridLayout(8,2,40,40));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

lbl1=new JLabel("Enter a City Name :");


lbl2=new JLabel("Enter a STD CODE :");
txt1=new JTextField(20);
txt2=new JTextField(20);
add=new JButton("ADD");
remove=new JButton("REMOVE");
search=new JButton("SEARCH");
add(lbl1);
add(txt1);
add(lbl2);
add(txt2);
add(add);
add(remove);
add(search);
setVisible(true);
add.addActionListener(this);
remove.addActionListener(this);
search.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==add){
String city=(txt1.getText());
String std=(txt2.getText());
hash.put(city,std);
txt1.setText("");
txt2.setText("");
JOptionPane.showMessageDialog(null,"Succesfully
Inserted",city,JOptionPane.INFORMATION_MESSAGE);
}
if(ae.getSource()==remove){
String city=(txt1.getText());
hash.remove(city);
txt1.setText("");
txt2.setText("");
JOptionPane.showMessageDialog(null,"Succesfully
Removed",city,JOptionPane.INFORMATION_MESSAGE);
}
if(ae.getSource()==search){
String city=(txt1.getText());
if(hash.containsKey(city)){
System.out.println(hash);

txt2.setText(hash.get(city));
JOptionPane.showMessageDialog(null,"Succesfully
Printed",city,JOptionPane.INFORMATION_MESSAGE);
}else{
System.out.println("Sorry this city can not be found!");
}
}
}
}

class setc1
{
public static void main(String args[]){
demo obj=new demo();
}
}

2) Write a program to create link list of integer objects. Do the following:


i. add element at first position
ii. delete last element
iii. display the size of link list
import java.util.*;
class setc2{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
LinkedList ll=new LinkedList();
System.out.println("How many number");
int n=input.nextInt();
System.out.println("Enter integer");
for(int i=0;i<n;i++){
ll.add(input.nextInt());
}
System.out.println("original linked list "+ll);
while(true){
System.out.println("\nMenu of program\n");
System.out.println("\n1.Add element at first position\n2.Delete last element\n3.display the size of
linked list\n");
System.out.println("Enter your choice");
int ch=input.nextInt();

switch(ch){
case 1:
System.out.println("Enter element to add");
int ele=input.nextInt();
ll.addFirst(ele);
System.out.println("Added element is "+ll);
break;
case 2:
ll.removeLast();
System.out.println("deleted element is "+ll);
break;
case 3:
System.out.println("size of linked list is "+ll.size());
break;
case 4:
System.exit(1);
}
}
}
}
/*************output***********
bcs@localhost:~/Desktop/TY2sem/java/assi1/setc> javac setc2.java
Note: setc2.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
bcs@localhost:~/Desktop/TY2sem/java/assi1/setc> java setc2
How many number
3
Enter integer
1
2
3
original linked list [1, 2, 3]

Menu of program

1.Add element at first position


2.Delete last element
3.display the size of linked list

Enter your choice


1
Enter element to add
2
Added element is [2, 1, 2, 3]

Menu of program

1.Add element at first position


2.Delete last element
3.display the size of linked list

Enter your choice


2
deleted element is [2, 1, 2]

Menu of program

1.Add element at first position


2.Delete last element
3.display the size of linked list

Enter your choice


3
size of linked list is 3

Menu of program
1.Add element at first position
2.Delete last element
3.display the size of linked list

Enter your choice


3
size of linked list is 3

Menu of program

1.Add element at first position


2.Delete last element
3.display the size of linked list

Enter your choice


4
*/

3) Read a text file, specified by the first command line argument, into a list. The
program should then display a menu which performs the following operations on
the list:

import java.util.*;
import java.io.*;
class setc3{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
try{
File f=new File(args[0]);
BufferedReader br=null;
br=new BufferedReader(new FileReader(f));

int ch;
LinkedList al=new LinkedList();

String line="";
while((line=br.readLine())!=null){
al.add(line);
}
while(true){
System.out.println("1.Insert Line\n 2.Delete Line\n3.Append Line\n4.modify Line\n5.Exit");
System.out.println("Enter chioce:");
ch=sc.nextInt();
String ll="this is a new Line";
switch(ch){
case 1:

System.out.println("Enter line:");
sc.nextLine();
String c=sc.nextLine();
al.add(c);
System.out.println("Content added ");
System.out.println(al);
break;

case 2:
al.remove(ll);
break;

case 3:
al.add(ll);
break;

case 4:
int n=al.size()-1;
al.set(n,"\tUpdated line");
break;

case 5:
ListIterator li=al.listIterator();
FileOutputStream fout=new FileOutputStream(args[0]);
while(li.hasNext()){
String l2=(String)li.next();
byte b[]=l2.getBytes();
fout.write(b);
}

break;

}
catch(Exception e){
System.out.println(e);
}

}
}

multithreading
SET A
1) Program to define a thread for printing text on output screen for ‘n’ number of times.
Create 3 threads and run them. Pass the text ‘n’ parameters to the thread constructor.
Example:
i. First thread prints “COVID19” 10 times.
ii. Second thread prints “LOCKDOWN2020” 20 times
iii. Third thread prints “VACCINATED2021” 30 times

public class seta1 extends Thread


{
String str;
int n;
A1(String str,int n)
{
this.str=str;
this.n=n;
}
public void run()
{
try
{
for(int i=0;i<n;i++)
{
System.out.println(getName()+":"+str);
}
}

catch(Exception e)
{
e.printStackTrace();
}
}

public static void main(String args[])


{
A1 t1=new A1("COVID",10);
t1.start();
A1 t2=new A1("LOCKDOWN",20);
t2.start();
A1 t3=new A1("VACCINE",30);
t3.start();
}
}

2) Write a program in which thread sleep for 6 sec in the loop in reverse order from 100
to 1 and change the name of thread.

public class A2
{
public static void main(String args[])
{
try
{
Thread t=new Thread();
t.setName("revese order");
System.out.println(t);
for(int i=100;i>=1;i--)
{
System.out.println(i);
t.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

3) Write a program to solve producer consumer problem in which a producer produces


a value and consumer consume the value before producer generate the next value.
(Hint: use thread synchronization)

class shop
{
int material;
boolean flag=false;

public synchronized int get()


{
while(flag==false)
{
try
{
wait();
}
catch(Exception e)
{
e.getStackTrace();
}//catch
}//while
flag=false;
notify();
return material;
}//get

public synchronized void put(int value)


{
while(flag==true)
{
try
{
wait();
}
catch(Exception e)
{
e.getStackTrace();
}//catch
}//while
material=value;
flag=true;
notify();
}//put
}//shop

class consumer extends Thread


{
shop sh;
int no;
public consumer(shop shp,int no)
{
sh=shp;
this.no=no;
}
public void run()
{
int value=0;
for(int i=0;i<10;i++)
{
value=sh.get();
System.out.println("consumer : " +this.no+ "get :" +value);
}//for
}//run
}//consumer

class producer extends Thread


{
shop sh;
int no;
public producer(shop s,int no)
{
sh=s;
this.no=no;
}
public void run()
{
int value=0;
for(int i=0;i<10;i++)
{
sh.put(i);
System.out.println("producer : " +this.no+ "put :" +i);
try
{
sleep((int) (Math.random() *1000));
}
catch(Exception e)
{
System.out.println(e);
}//catch
}//for
}//run
}//producer

public class s
{
public static void main(String args[])
{
shop s=new shop();
producer p=new producer(s,1);
consumer c=new consumer(s,1);
p.start();
c.start();
}
}

SET B
1) Write a program to calculate the sum and average of an array of 1000 integers
(generated randomly) using 10 threads. Each thread calculates the sum of 100
integers. Use these values to calculate average. [Use join method ].

import java.util.*;
class sumthread implements Runnable
{
Thread t;
int a[]=new int[1000];
int no,sum;
sumthread(String s,int n)
{
Random r=new Random();
t=new Thread(this,s);
int j=0;
no=n;
for(int i=0;i<100;i++)
{
a[i]=r.nextInt(100);
j++;
}
t.start();
}//sumthread
public void run()
{
try
{
for(int i=0;i<10;i++)
{
System.out.print(a[no]+" ");
sum=sum+a[no];
no++;
}
System.out.println(" ");
System.out.println(" SUM: "+sum);
System.out.println(" AVG: "+sum/10);
System.out.println(" ");
}//try
catch(Exception e)
{
System.out.println(e);
}
}
}//class

public class setb1


{
public static void main(String args[])
{
try
{
sumthread t1=new sumthread("t1", 1);
t1.t.join();

sumthread t2=new sumthread("t2", 10);


t2.t.join();

sumthread t3=new sumthread("t3", 20);


t3.t.join();

sumthread t4=new sumthread("t4", 30);


t4.t.join();

sumthread t5=new sumthread("t5", 40);


t5.t.join();

sumthread t6=new sumthread("t6", 50);


t6.t.join();

sumthread t7=new sumthread("t7", 60);


t7.t.join();

sumthread t8=new sumthread("t8", 70);


t8.t.join();

sumthread t9=new sumthread("t9", 80);


t9.t.join();

sumthread t10=new sumthread("t10", 90);


t10.t.join();
}//try
catch(Exception e)
{
System.out.println(e);
}//catch
}
}

2) Write a program for a simple search engine. Accept a string to be searched. Search for
the string in all text files in the current folder. Use a separate thread for each file. The
result should display the filename, line number where the string is found.

import java.io.*;
import java.util.*;

class threadb2 extends Thread{

public threadb2(String name){


super(name);
}
public void cheak(String name){

try{

File Directory=new File("/home/bcs/Desktop/Anuja_gorde");


String list[]=Directory.list();
for(int i=0; i<list.length; i++){
File f=new File(list[i]);
FileReader fr=new FileReader(f);
BufferedReader br= new BufferedReader(fr);
String ch;
int line=0;
String txtFile=null;
while ((ch = br.readLine()) != null){
if(ch.equals("\n")){
line++;

}
if(ch.equals(name)){
System.out.print("Found in :"+list[i]+"\n");
System.out.print("Found line no:"+line+"\n");
}

}
}

}catch(Exception e){

System.out.println(e);

}
}

public static void main(String main[])throws Exception{

Scanner input=new Scanner(System.in);

System.out.println("Enter a name of string to be search");


String search=input.nextLine();
threadb2 th1=new threadb2("a.txt");
th1.cheak(search);

}
}

3) Write a program that implements a multi-thread application that has three threads.
First thread generates random integer every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the
third thread will print the value of cube of the number.
import java.util.*;
class FirstThead extends Thread
{
Random r=new Random();
public int n;

public void run()


{
try
{
for(int i=0;i<10;i++)

{
n=r.nextInt(10);
System.out.println("generated random number : " +n);
if(n % 2 ==0)
{
SecondThread t2=new SecondThread(n);
t2.start();
}
else
{
ThirdThread t3=new ThirdThread(n);
t3.start();
}
sleep(1000);
}//for
}
catch(Exception e)
{
System.out.println(e);
}//catch
}//run
}//Firstthread

class SecondThread extends Thread


{
int square;
SecondThread(int n)
{
square=n*n;
}
public void run()
{
System.out.println("Square number is : " +square);
}//run
}//Secondthread

class ThirdThread extends Thread


{
int cube;
ThirdThread(int n)
{
cube=n*n*n;
}

public void run()


{
System.out.println("cube number is : " +cube);
}//run
}//Secondthread
public class B3
{
public static void main(String args[])
{
FirstThead t1=new FirstThead();
t1.start();
}
}

SET C
1) Write a program that implements a multi-thread application that has three threads.
First thread generates random integer every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the
third thread will print the value of cube of the number.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class c1 extends JFrame implements ActionListener
{
JPanel panel=new JPanel();
JPanel title_lbl=new JPanel("Traffic Light");
JRadioButton rb1=new JRadioButton("Red");
JRadioButton rb2=new JRadioButton("Yellow");
JRadioButton rb3=new JRadioButton("Green");
JButton ok_btn=new JButton("ok");
ButtonGroup g1=new ButtonGroup();
JLabel red;
JLabel yellow;
JLabel green;

c1()
{
setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
setSize(800,150);
setTitle("java Project Program");
setLocation(400,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
red=new JLabel("STOP");
red.setForeground(Color.red);
yellow=new JLabel("READy");
yellow.setForeground(Color.yellow);
green=new JLabel("GO");
green.setForeground(Color.green);
Panel.setPreferredSize(new Dimension(500,400));
Panel.setLayout(null);
Panel.setBackground(color.green);
panel.setforeground(color.lightGray);
title_lbl.setBounds(200,0,200,100);
Panel.add(title_lbl);

rb1.setBounds(200,0,200,200);
Panel.add(rb1);
rb2.setBounds(200,0,200,200);
Panel.add(rb2);
rb3.setBounds(200,0,200,200);
Panel.add(rb3);
ok_btn.setBounds(200,310,100,50);
Panel.add(ok_btn);
ok_btn.addActionListener(this);
red.setBounds(200,110,100,50);
yellow.setBounds(200,110,100,50);
green.setBounds(200,110,100,50);

rb1.setForeground(Color,red);
rb2.setForeground(Color,yellow);
rb3.setForeground(Color,green);

rb1.setBackground(Color,lightGray);
rb2.setBackground(Color,lightGray);
rb3.setBackground(Color,lightGray);

red.setFont(new Font("Arial",Font.BOLD,20));
yellow.setFont(new Font("Arial",Font.BOLD,20));
green.setFont(new Font("Arial",Font.BOLD,20));
title_lbl.setFont(new Font ("Arial",Font.BOLD,20));
Panel.add(red);
Panel.add(yellow);
Panel.add(green);

red.setVisible(false);
yellow.setVisible(false);
green.setVisible(false);

g1.add(rb1);
g1.add(rb2);
g1.add(rb3);
this.add(Panel);
this.pack();
setVisible(true);
}
public void ActionPerformed(ActionPerformed ae)
{
if(ae.getSource() == ok_btn)
{
if(rb1.isSelected())
{
yellow.setVisible(false);
green.setVisible(false);
red.setVisible(true);
}
else if(rb2.isSelected())
{
red.setVisible(false);
green.setVisible(false);
yellow.setVisible(true);
}
if(rb3.isSelected())
{
red.setVisible(false);
yellow.setVisible(false);
green.setVisible(true);
}
}
}
public static void main(String args[])
{
new c1();
}
}

2) Write a program to create a thread for moving a ball inside a panel vertically. The
ball should be created when the user clicks on the start button.

class shop
{
//int material;
boolean flag=false;

public synchronized void sendor(String msg)


{
if(flag)
{
try
{
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}//catch
}//while
System.out.println(msg);
flag=true;
notify();
}//get

public synchronized void receiver(String msg)


{
if(!flag)
{
try
{
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}//catch
}//while
System.out.println(msg);
flag=false;
notify();
}//get
}//shop

class t1 implements Runnable


{
String s1[]={"hi","how are you"};
public t1(chat m);
{
this.m=m1;
new Thread(this,"sendor").start();
}
public void run()
{
for(int i=0;i<s1.length;i++)
{
m.sendor(s1[i]);
}//for
}//run
}//consumer

class t2 implements Runnable


{
String s1[]={"GOOD BYE CORONA"};
public t2(chat m2);
{
this.m=m2;
new Thread(this,"receiver").start();
}
public void run()
{
for(int i=0;i<s1.length;i++)
{
m.receiver(s1[i]);
}//for
}//run
}//consumer
public class s
{
public static void main(String args[])
{
chat m=new chat();
new t1(m);
new t2(m);
}
}

You might also like