SlideShare una empresa de Scribd logo
1 de 15
Descargar para leer sin conexión
(1) Java Program toFind duplicates and unique set
Example Input :
an array of String contains :String[] str = new String[] {"alok", "dhoni", "manish", "rajiv", "alok",
"rajiv"}
output :
unique items: [manish, dhoni]
Duplicate items : [alok, rajiv]
SetExampl.java
package com.alok.Uniqueduplicate;
import java.util.HashSet;
import java.util.Set;
public class SetExample
{
public static void main(String[] args)
{
String[] str = new String[]
{"alok", "dhoni", "manish", "rajiv", "alok", "rajiv"};
Set<String> duplicateSet = new HashSet<String>();
Set<String> uniqueSet = new HashSet<String>();
for(int i = 0; i < str.length ; i++ )
{
if(!uniqueSet.add(str[i]))
{
duplicateSet.add(str[i]);
}
}
uniqueSet.removeAll(duplicateSet);
System.out.println("unique items: "+uniqueSet);
System.out.println("Duplicate items : "+ duplicateSet);
}
}
output :
unique items: [manish, dhoni]
Duplicate items : [alok, rajiv]
(2) create an entity class "Product" with following properties
product_id, product_name, product_details, price. Add
some sample data in this product class using collections.
and sort and display
create an entity class "Product" with following properties product_id, product_name,
product_details, price. Add some sample data in this product class
using collections. and sort and display :
-->on default by product_id
-->based on product_name or price
-->sort on product_name, if two product_name is same sort on product_details basis.
-->sort on price, if two prices are same consider sorting on product_id basis.
Product.java
package com.test;
import java.util.Comparator;
public class Product implements Comparable<Product>{
private int productId;
private String productName;
private String productDescription;
private double price;
public Product()
{
}
public Product(int productId, String productName, String
productDescription, double price)
{
this.productId = productId;
this.productName = productName;
this.productDescription = productDescription;
this.price = price;
}
public int getProductId()
{
return productId;
}
public void setProductId(int productId)
{
this.productId = productId;
}
public String getProductName()
{
return productName;
}
public void setProductName(String productName)
{
this.productName = productName;
}
public String getProductDescription()
{
return productDescription;
}
public void setProductDescription(String productDescription)
{
this.productDescription = productDescription;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
@Override
public int compareTo(Product p)
{
return this.productId-p.productId;
}
@Override
public String toString()
{
return "price= " + price + ", productDescription= "
+ productDescription + ", productId= " + productId
+ ", productName= " + productName;
}
public static class ProductInnerClass implements Comparator<Product>
{
@Override
public int compare(Product p1, Product p2)
{
int i=Double.compare(p1.getPrice(), p2.getPrice());
if(i==0)
{
return p1.getProductId()-p2.getProductId();
}
return i;
}
}
}
ProductMain.java
package com.alok.entity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.alok.client.Product;
public class ProductMain {
public static void main(String[] args) throws NumberFormatException,
IOException {
ArrayList<Product> productList=new ArrayList<Product>();
productList.add(new Product(555, "Monitor", "15 inch", 4000.00));
productList.add(new Product(2222, "Monitor", "17 inch", 5000.00));
productList.add(new Product(3333, "Del", "Laptop", 4000.00));
productList.add(new Product(6666, "Mouse", "Optical Mouse", 200.00));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)
);
int i=1;
while(i<3)
{
System.out.println("1 : Sort by id");
System.out.println("2 : Sort by name");
System.out.println("3 : Sort by price");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1 : Collections.sort(productList);
System.out.println("Sorted product : ");
for(Product p : productList)
{
System.out.println(p);
}
break;
case 2 :
Collections.sort(productList, new Comparator<Product>()
{
@Override
public int compare(Product p1, Product p2)
{
int i=p1.getProductName().compareToIgnoreCase
(p2.getProductName());
if(i==0)
{
return p1.getProductDescription().
compareToIgnoreCase(p2.getProductDescription());
}
return i;
}
});
System.out.println("Sorted product : ");
for(Product p : productList)
{
System.out.println(p);
}
break;
case 3 :
Collections.sort(productList,new Product.ProductInnerClass());
System.out.println("Sorted product : ");
for(Product p : productList)
{
System.out.println(p);
}
break;
default : System.out.println("Invalid Option");
System.exit(0);
}
}
}
}
OUTPUT:
1 : Sort by id
2 : Sort by name
3 : Sort by price
1
Sorted product :
price= 4000.0, productDescription= 15 inch, productId= 555,
productName= Monitor
price= 5000.0, productDescription= 17 inch, productId= 2222,
productName= Monitor
price= 4000.0, productDescription= Laptop, productId= 3333,
productName= Del
price= 200.0, productDescription= Optical Mouse, productId= 6666,
productName= Mouse
1 : Sort by id
2 : Sort by name
3 : Sort by price
2
Sorted product :
price= 4000.0, productDescription= Laptop, productId= 3333,
productName= Del
price= 4000.0, productDescription= 15 inch, productId= 555,
productName= Monitor
price= 5000.0, productDescription= 17 inch, productId= 2222,
productName= Monitor
price= 200.0, productDescription= Optical Mouse, productId= 6666,
productName= Mouse
1 : Sort by id
2 : Sort by name
3 : Sort by price
3
Sorted product :
price= 200.0, productDescription= Optical Mouse, productId= 6666,
productName= Mouse
price= 4000.0, productDescription= 15 inch, productId= 555,
productName= Monitor
price= 4000.0, productDescription= Laptop, productId= 3333,
productName= Del
price= 5000.0, productDescription= 17 inch, productId= 2222,
productName= Monitor
1 : Sort by id
2 : Sort by name
3 : Sort by price
4
Invalid Option
(3) Writte a JAVA program to merge two files by taking
input as two .txt file and Display Files Contents In Third
File
sample..
............
input file:
input1.txt
Ram is a good boy
input2.txt
He is Very poor
output file:
output.txt
Ram is a good boy
He is very poor
CombineTwoFile.java
package com.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "input1.txt"));
BufferedReader r
= new BufferedReader(new FileReader( "input2.txt"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("output.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("n");
}
System.out.println("complited");
writer.close();
}
}
(4) Read a file and count the no of occurance of specific
word
Example Input file
input.txt
class Employee
{
private String name;
public Integer age;
protected Date dob;
public Address addr;
private Date doj;
public String designation;
}
SpecificWordCount.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
public class SpecificWordCount
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new FileReader("input.txt"));
String ch=null;
int count=0;
try
{
HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("public", count);
hmap.put("private", count);
hmap.put("protected", count);
while((ch=br.readLine())!=null)
{
String[] word=ch.split(" ");
for(int i=0;i<word.length;i++)
{
if (word[i].equalsIgnoreCase("public"))
{
int value=hmap.get("public");
value++;
hmap.put("public", value);
}
if (word[i].equalsIgnoreCase("private"))
{
int value=hmap.get("private");
value++;
hmap.put("private", value);
}
if (word[i].equalsIgnoreCase("protected"))
{
int value=hmap.get("protected");
value++;
hmap.put("protected", value);
}
}
}
Set<String> keySet=hmap.keySet();
for(String key : keySet)
{
int value=hmap.get(key);
System.out.println(key + "-->" + value);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
output:
protected-->1
public-->3
private-->2
(5) Take a file as input, get the value from file and insert it
in a ArrayList after inserting write all the values of list in
other file...
sample:
Input file: input.txt
class Employee
{
private String name;
public Integer age;
protected Date dob;
public Address addr;
private Date doj;
public String designation;
}
output file: output.txt(Empty file)
InputFile.java
package com.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class InputFil
{
public static void main(String[] args) throws IOException
{
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File Name:");
String fname=br.readLine();
try
{
@SuppressWarnings("unused")
FileInputStream f=new FileInputStream(fname);
System.out.println("*********************************************
********");
System.out.println("content of file are:");
System.out.println("************************");
FileReader file=new FileReader(fname);
BufferedReader b=new BufferedReader(file);
String s1=b.readLine();
while(s1!=null)
{
System.out.println(s1);
s1=b.readLine();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not Found");
return;
}
System.out.println("*************************************************
****");
ArrayList<String>rows = new ArrayList<String>();
try {
System.out.println("*********************************************
********");
System.out.println("In Array List :");
System.out.println("*******************");
BufferedReader r = new BufferedReader(new FileReader(
fname));
String line = null;
while ((line = r.readLine()) != null)
{
String[] arr=line.split("s+");
rows.add(line);
}
System.out.println(rows.toString());
} catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("output.txt"));
//ObjectOutputStream out = new ObjectOutputStream((output));
String listWord;
for (int i = 0; i< rows.size(); i++)
{
listWord = rows.get(i);
writer.write(listWord);
writer.write("n");
}
writer.close();
}
}
output of program
Enter File Name:
input.txt
*****************************************************
content of file are:
************************
class Employee
{
private String name;
public Integer age;
protected Date dob;
public Address addr;
private Date doj;
public String designation;
}
*****************************************************
*****************************************************
In Array List :
*******************
[class Employee, {, private String name;, public Integer age;, protected Date dob;, public
Address addr;, private Date doj;, public String designation;, , }]
open output.txt (we can see all data in input.txt now available in output.txt)
class Employee
{
private String name;
public Integer age;
protected Date dob;
public Address addr;
private Date doj;
public String designation;
}
(6) Java Program To Print Consecutive characters and the
number of times it occurs in ascending order of number
of occurrences
Sample
-----------
input : “I saw a cd player and a modem in ccd”
output : de--> 1
cd --> 2
I saw a player and a mom in c
ContiAlpha.java
package com.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
public class ContiAlpha
{
public static void main(String[] args) throws IOException
{
try
{
HashMap<String, Integer> map= new HashMap<String, Integer>();
String s1="I saw a cd ghplayer and a modem degh in ccd";
s1=s1.toLowerCase();
for(int i=0;i<(s1.length()-1);i++)
{
if(s1.charAt(i+1)-s1.charAt(i)==1)
{
String word=s1.charAt(i)+""+s1.charAt(i+1);
if(map.containsKey(word))
{
int value=map.get(word);
map.put(word,++value);
}
else
{
map.put(word, 1);
}
}
}
ArrayList<ContiSortByValue> list=new ArrayList<ContiSortByValue>();
Set<String> keySet=map.keySet();
String s2=s1;
for(String k : keySet)
{
s2=s2.replace(k, "");
int value=map.get(k);
list.add(new ContiSortByValue(k, value));
}
System.out.println(s2);
Collections.sort(list);
for(ContiSortByValue sort : list)
{
System.out.println(sort);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
ContiSortByValue.java
package com.test;
public class ContiSortByValue implements Comparable<ContiSortByValue>
{
private String key;
private Integer value;
public ContiSortByValue()
{
// TODO Auto-generated constructor stub
}
public ContiSortByValue(String key, Integer value)
{
super();
this.key = key;
this.value = value;
}
@Override
public int compareTo(ContiSortByValue obj)
{
return this.value - obj.value;
}
@Override
public String toString()
{
return key + "-->" + value;
}
}
output:
de-->1
cd-->2
i saw a player and a mom in c

Más contenido relacionado

La actualidad más candente

Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
New Relic
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 

La actualidad más candente (20)

Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java practical
Java practicalJava practical
Java practical
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 

Destacado

66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
Laura Popovici
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 

Destacado (20)

Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overriding
 
Normalization
NormalizationNormalization
Normalization
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Normalization.riz
Normalization.rizNormalization.riz
Normalization.riz
 
Lis124
Lis124Lis124
Lis124
 
Lecture8 Normalization Aggarwal
Lecture8 Normalization AggarwalLecture8 Normalization Aggarwal
Lecture8 Normalization Aggarwal
 
Normalization 1 nf,2nf,3nf,bcnf
Normalization 1 nf,2nf,3nf,bcnf Normalization 1 nf,2nf,3nf,bcnf
Normalization 1 nf,2nf,3nf,bcnf
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Compiler design lab programs
Compiler design lab programs Compiler design lab programs
Compiler design lab programs
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Java codes
Java codesJava codes
Java codes
 
Normalization in DBMS
Normalization in DBMSNormalization in DBMS
Normalization in DBMS
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Mest 1 guidance
Mest 1 guidanceMest 1 guidance
Mest 1 guidance
 
Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 

Similar a Important java programs(collection+file)

I can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docxI can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docx
hamblymarta
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Object oriented programming la bmanual jntu
Object oriented programming la bmanual jntuObject oriented programming la bmanual jntu
Object oriented programming la bmanual jntu
Khurshid Asghar
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdf
fantoosh1
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdf
manojmozy
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 

Similar a Important java programs(collection+file) (20)

Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Bhaloo
BhalooBhaloo
Bhaloo
 
I can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docxI can not get my code to comply it gets mad that I have run declare mo.docx
I can not get my code to comply it gets mad that I have run declare mo.docx
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Object oriented programming la bmanual jntu
Object oriented programming la bmanual jntuObject oriented programming la bmanual jntu
Object oriented programming la bmanual jntu
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdf
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
Elementary Sort
Elementary SortElementary Sort
Elementary Sort
 
Java ppt
Java pptJava ppt
Java ppt
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdf
 
Python tour
Python tourPython tour
Python tour
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Lab4
Lab4Lab4
Lab4
 
• GUI design using drag and drop feature of IDE(Net beans), • File IO
•	GUI design using drag and drop feature of IDE(Net beans), •	File IO•	GUI design using drag and drop feature of IDE(Net beans), •	File IO
• GUI design using drag and drop feature of IDE(Net beans), • File IO
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
 

Último

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Important java programs(collection+file)

  • 1. (1) Java Program toFind duplicates and unique set Example Input : an array of String contains :String[] str = new String[] {"alok", "dhoni", "manish", "rajiv", "alok", "rajiv"} output : unique items: [manish, dhoni] Duplicate items : [alok, rajiv] SetExampl.java package com.alok.Uniqueduplicate; import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { String[] str = new String[] {"alok", "dhoni", "manish", "rajiv", "alok", "rajiv"}; Set<String> duplicateSet = new HashSet<String>(); Set<String> uniqueSet = new HashSet<String>(); for(int i = 0; i < str.length ; i++ ) { if(!uniqueSet.add(str[i])) { duplicateSet.add(str[i]); } } uniqueSet.removeAll(duplicateSet); System.out.println("unique items: "+uniqueSet); System.out.println("Duplicate items : "+ duplicateSet); } } output : unique items: [manish, dhoni] Duplicate items : [alok, rajiv]
  • 2. (2) create an entity class "Product" with following properties product_id, product_name, product_details, price. Add some sample data in this product class using collections. and sort and display create an entity class "Product" with following properties product_id, product_name, product_details, price. Add some sample data in this product class using collections. and sort and display : -->on default by product_id -->based on product_name or price -->sort on product_name, if two product_name is same sort on product_details basis. -->sort on price, if two prices are same consider sorting on product_id basis. Product.java package com.test; import java.util.Comparator; public class Product implements Comparable<Product>{ private int productId; private String productName; private String productDescription; private double price; public Product() { } public Product(int productId, String productName, String productDescription, double price) { this.productId = productId; this.productName = productName; this.productDescription = productDescription; this.price = price; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getProductName()
  • 3. { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductDescription() { return productDescription; } public void setProductDescription(String productDescription) { this.productDescription = productDescription; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public int compareTo(Product p) { return this.productId-p.productId; } @Override public String toString() { return "price= " + price + ", productDescription= " + productDescription + ", productId= " + productId + ", productName= " + productName; } public static class ProductInnerClass implements Comparator<Product> { @Override public int compare(Product p1, Product p2) { int i=Double.compare(p1.getPrice(), p2.getPrice()); if(i==0) { return p1.getProductId()-p2.getProductId(); } return i;
  • 4. } } } ProductMain.java package com.alok.entity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import com.alok.client.Product; public class ProductMain { public static void main(String[] args) throws NumberFormatException, IOException { ArrayList<Product> productList=new ArrayList<Product>(); productList.add(new Product(555, "Monitor", "15 inch", 4000.00)); productList.add(new Product(2222, "Monitor", "17 inch", 5000.00)); productList.add(new Product(3333, "Del", "Laptop", 4000.00)); productList.add(new Product(6666, "Mouse", "Optical Mouse", 200.00)); BufferedReader br=new BufferedReader(new InputStreamReader(System.in) ); int i=1; while(i<3) { System.out.println("1 : Sort by id"); System.out.println("2 : Sort by name"); System.out.println("3 : Sort by price"); int ch=Integer.parseInt(br.readLine()); switch(ch) { case 1 : Collections.sort(productList); System.out.println("Sorted product : "); for(Product p : productList) { System.out.println(p); } break; case 2 : Collections.sort(productList, new Comparator<Product>() { @Override public int compare(Product p1, Product p2)
  • 5. { int i=p1.getProductName().compareToIgnoreCase (p2.getProductName()); if(i==0) { return p1.getProductDescription(). compareToIgnoreCase(p2.getProductDescription()); } return i; } }); System.out.println("Sorted product : "); for(Product p : productList) { System.out.println(p); } break; case 3 : Collections.sort(productList,new Product.ProductInnerClass()); System.out.println("Sorted product : "); for(Product p : productList) { System.out.println(p); } break; default : System.out.println("Invalid Option"); System.exit(0); } } } } OUTPUT: 1 : Sort by id 2 : Sort by name 3 : Sort by price 1 Sorted product : price= 4000.0, productDescription= 15 inch, productId= 555, productName= Monitor price= 5000.0, productDescription= 17 inch, productId= 2222, productName= Monitor price= 4000.0, productDescription= Laptop, productId= 3333, productName= Del
  • 6. price= 200.0, productDescription= Optical Mouse, productId= 6666, productName= Mouse 1 : Sort by id 2 : Sort by name 3 : Sort by price 2 Sorted product : price= 4000.0, productDescription= Laptop, productId= 3333, productName= Del price= 4000.0, productDescription= 15 inch, productId= 555, productName= Monitor price= 5000.0, productDescription= 17 inch, productId= 2222, productName= Monitor price= 200.0, productDescription= Optical Mouse, productId= 6666, productName= Mouse 1 : Sort by id 2 : Sort by name 3 : Sort by price 3 Sorted product : price= 200.0, productDescription= Optical Mouse, productId= 6666, productName= Mouse price= 4000.0, productDescription= 15 inch, productId= 555, productName= Monitor price= 4000.0, productDescription= Laptop, productId= 3333, productName= Del price= 5000.0, productDescription= 17 inch, productId= 2222, productName= Monitor 1 : Sort by id 2 : Sort by name 3 : Sort by price 4 Invalid Option
  • 7. (3) Writte a JAVA program to merge two files by taking input as two .txt file and Display Files Contents In Third File sample.. ............ input file: input1.txt Ram is a good boy input2.txt He is Very poor output file: output.txt Ram is a good boy He is very poor CombineTwoFile.java package com.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class CombineTwoFile { public static void main(String[] args) throws IOException { ArrayList<String> list = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new FileReader( "input1.txt")); BufferedReader r = new BufferedReader(new FileReader( "input2.txt")); String s1 =null; String s2 = null;
  • 8. while ((s1 = br.readLine()) != null) { list.add(s1); } while((s2 = r.readLine()) != null) { list.add(s2); } } catch (IOException e) { e.printStackTrace(); } BufferedWriter writer=null; writer = new BufferedWriter(new FileWriter("output.txt")); String listWord; for (int i = 0; i< list.size(); i++) { listWord = list.get(i); writer.write(listWord); writer.write("n"); } System.out.println("complited"); writer.close(); } } (4) Read a file and count the no of occurance of specific word Example Input file input.txt class Employee { private String name; public Integer age; protected Date dob; public Address addr; private Date doj; public String designation;
  • 9. } SpecificWordCount.java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Set; public class SpecificWordCount { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader("input.txt")); String ch=null; int count=0; try { HashMap<String, Integer> hmap = new HashMap<String, Integer>(); hmap.put("public", count); hmap.put("private", count); hmap.put("protected", count); while((ch=br.readLine())!=null) { String[] word=ch.split(" "); for(int i=0;i<word.length;i++) { if (word[i].equalsIgnoreCase("public")) { int value=hmap.get("public"); value++; hmap.put("public", value); } if (word[i].equalsIgnoreCase("private")) { int value=hmap.get("private"); value++; hmap.put("private", value); } if (word[i].equalsIgnoreCase("protected")) {
  • 10. int value=hmap.get("protected"); value++; hmap.put("protected", value); } } } Set<String> keySet=hmap.keySet(); for(String key : keySet) { int value=hmap.get(key); System.out.println(key + "-->" + value); } } catch(Exception e) { e.printStackTrace(); } } output: protected-->1 public-->3 private-->2 (5) Take a file as input, get the value from file and insert it in a ArrayList after inserting write all the values of list in other file... sample: Input file: input.txt class Employee { private String name; public Integer age; protected Date dob; public Address addr; private Date doj; public String designation;
  • 11. } output file: output.txt(Empty file) InputFile.java package com.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.util.ArrayList; public class InputFil { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter File Name:"); String fname=br.readLine(); try { @SuppressWarnings("unused") FileInputStream f=new FileInputStream(fname); System.out.println("********************************************* ********"); System.out.println("content of file are:"); System.out.println("************************"); FileReader file=new FileReader(fname); BufferedReader b=new BufferedReader(file); String s1=b.readLine(); while(s1!=null) { System.out.println(s1); s1=b.readLine(); } } catch(FileNotFoundException e) { System.out.println("File not Found");
  • 12. return; } System.out.println("************************************************* ****"); ArrayList<String>rows = new ArrayList<String>(); try { System.out.println("********************************************* ********"); System.out.println("In Array List :"); System.out.println("*******************"); BufferedReader r = new BufferedReader(new FileReader( fname)); String line = null; while ((line = r.readLine()) != null) { String[] arr=line.split("s+"); rows.add(line); } System.out.println(rows.toString()); } catch (IOException e) { e.printStackTrace(); } BufferedWriter writer=null; writer = new BufferedWriter(new FileWriter("output.txt")); //ObjectOutputStream out = new ObjectOutputStream((output)); String listWord; for (int i = 0; i< rows.size(); i++) { listWord = rows.get(i); writer.write(listWord); writer.write("n"); } writer.close(); } } output of program Enter File Name: input.txt ***************************************************** content of file are: ************************ class Employee
  • 13. { private String name; public Integer age; protected Date dob; public Address addr; private Date doj; public String designation; } ***************************************************** ***************************************************** In Array List : ******************* [class Employee, {, private String name;, public Integer age;, protected Date dob;, public Address addr;, private Date doj;, public String designation;, , }] open output.txt (we can see all data in input.txt now available in output.txt) class Employee { private String name; public Integer age; protected Date dob; public Address addr; private Date doj; public String designation; } (6) Java Program To Print Consecutive characters and the number of times it occurs in ascending order of number of occurrences Sample ----------- input : “I saw a cd player and a modem in ccd” output : de--> 1 cd --> 2 I saw a player and a mom in c
  • 14. ContiAlpha.java package com.test; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Set; public class ContiAlpha { public static void main(String[] args) throws IOException { try { HashMap<String, Integer> map= new HashMap<String, Integer>(); String s1="I saw a cd ghplayer and a modem degh in ccd"; s1=s1.toLowerCase(); for(int i=0;i<(s1.length()-1);i++) { if(s1.charAt(i+1)-s1.charAt(i)==1) { String word=s1.charAt(i)+""+s1.charAt(i+1); if(map.containsKey(word)) { int value=map.get(word); map.put(word,++value); } else { map.put(word, 1); } } } ArrayList<ContiSortByValue> list=new ArrayList<ContiSortByValue>(); Set<String> keySet=map.keySet(); String s2=s1; for(String k : keySet) { s2=s2.replace(k, ""); int value=map.get(k); list.add(new ContiSortByValue(k, value)); } System.out.println(s2); Collections.sort(list); for(ContiSortByValue sort : list) {
  • 15. System.out.println(sort); } } catch (Exception e) { e.printStackTrace(); } } } ContiSortByValue.java package com.test; public class ContiSortByValue implements Comparable<ContiSortByValue> { private String key; private Integer value; public ContiSortByValue() { // TODO Auto-generated constructor stub } public ContiSortByValue(String key, Integer value) { super(); this.key = key; this.value = value; } @Override public int compareTo(ContiSortByValue obj) { return this.value - obj.value; } @Override public String toString() { return key + "-->" + value; } } output: de-->1 cd-->2 i saw a player and a mom in c