SlideShare a Scribd company logo
(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

More Related Content

What's hot (20)

DOCX
Java PRACTICAL file
RACHIT_GUPTA
 
PPTX
Java Generics
Zülfikar Karakaya
 
PDF
Java programming-examples
Mumbai Academisc
 
PPTX
Unit Testing with Foq
Phillip Trelford
 
PDF
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
PDF
Java Class Design
Ganesh Samarthyam
 
PPTX
Java simple programs
VEERA RAGAVAN
 
ODP
Java Generics
Carol McDonald
 
PDF
Java Generics - by Example
Ganesh Samarthyam
 
ODT
Java practical
william otto
 
PPTX
Basic java, java collection Framework and Date Time API
jagriti srivastava
 
PDF
Java_practical_handbook
Manusha Dilan
 
KEY
Djangocon11: Monkeying around at New Relic
New Relic
 
DOC
Ad java prac sol set
Iram Ramrajkar
 
PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PDF
OOPs & Inheritance Notes
Shalabh Chaudhary
 
DOC
Advanced Java - Praticals
Fahad Shaikh
 
PPTX
Migrating to JUnit 5
Rafael Winterhalter
 
DOCX
Advance Java Programs skeleton
Iram Ramrajkar
 
PPTX
Use of Apache Commons and Utilities
Pramod Kumar
 
Java PRACTICAL file
RACHIT_GUPTA
 
Java Generics
Zülfikar Karakaya
 
Java programming-examples
Mumbai Academisc
 
Unit Testing with Foq
Phillip Trelford
 
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Java Class Design
Ganesh Samarthyam
 
Java simple programs
VEERA RAGAVAN
 
Java Generics
Carol McDonald
 
Java Generics - by Example
Ganesh Samarthyam
 
Java practical
william otto
 
Basic java, java collection Framework and Date Time API
jagriti srivastava
 
Java_practical_handbook
Manusha Dilan
 
Djangocon11: Monkeying around at New Relic
New Relic
 
Ad java prac sol set
Iram Ramrajkar
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Advanced Java - Praticals
Fahad Shaikh
 
Migrating to JUnit 5
Rafael Winterhalter
 
Advance Java Programs skeleton
Iram Ramrajkar
 
Use of Apache Commons and Utilities
Pramod Kumar
 

Viewers also liked (20)

PPTX
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
PDF
20 most important java programming interview questions
Gradeup
 
PPTX
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
DOCX
Differences between method overloading and method overriding
Pinky Anaya
 
KEY
Normalization
Ligaya Turmelle
 
PPT
Java IO Package and Streams
babak danyal
 
PPTX
Normalization.riz
Muhammad Imran Khan
 
PPTX
Lis124
Janecatalla
 
PPT
Lecture8 Normalization Aggarwal
anerudhbalaji
 
PPTX
Normalization 1 nf,2nf,3nf,bcnf
Shriya agrawal
 
PDF
66781291 java-lab-manual
Laura Popovici
 
PDF
Compiler design lab programs
Guru Janbheshver University, Hisar
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
DOCX
Java questions for viva
Vipul Naik
 
DOCX
Java codes
Hussain Sherwani
 
PPTX
Normalization in DBMS
Prateek Parimal
 
PPTX
Oop c++class(final).ppt
Alok Kumar
 
PPTX
Mest 1 guidance
Lee Hembling
 
PPTX
Database Normalization
Rathan Raj
 
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
20 most important java programming interview questions
Gradeup
 
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Differences between method overloading and method overriding
Pinky Anaya
 
Normalization
Ligaya Turmelle
 
Java IO Package and Streams
babak danyal
 
Normalization.riz
Muhammad Imran Khan
 
Lis124
Janecatalla
 
Lecture8 Normalization Aggarwal
anerudhbalaji
 
Normalization 1 nf,2nf,3nf,bcnf
Shriya agrawal
 
66781291 java-lab-manual
Laura Popovici
 
Compiler design lab programs
Guru Janbheshver University, Hisar
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java questions for viva
Vipul Naik
 
Java codes
Hussain Sherwani
 
Normalization in DBMS
Prateek Parimal
 
Oop c++class(final).ppt
Alok Kumar
 
Mest 1 guidance
Lee Hembling
 
Database Normalization
Rathan Raj
 
Ad

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

DOCX
Code red SUM
Shumail Haider
 
DOCX
Bhaloo
Shumail Haider
 
DOCX
I can not get my code to comply it gets mad that I have run declare mo.docx
hamblymarta
 
PDF
54240326 (1)
Vinayak Shedgeri
 
PDF
54240326 copy
Vinayak Shedgeri
 
DOCX
COLLECTION IN JAVA PROGRAMMING LANGUAGES
suryae1988
 
PPTX
Understanding java streams
Shahjahan Samoon
 
DOC
Object oriented programming la bmanual jntu
Khurshid Asghar
 
PDF
I need help with this code working Create another project and add yo.pdf
fantoosh1
 
PPS
Wrapper class
kamal kotecha
 
PPTX
Nice to meet Kotlin
Jieyi Wu
 
ZIP
Elementary Sort
Sri Prasanna
 
PPT
Java ppt
Rohan Gajre
 
PDF
import java.io.BufferedReader;import java.io.File;import java.io.pdf
manojmozy
 
PDF
Python tour
Tamer Abdul-Radi
 
PPTX
Java Programs
vvpadhu
 
PDF
Lab4
siragezeynu
 
DOCX
• GUI design using drag and drop feature of IDE(Net beans), • File IO
SyedShahroseSohail
 
PPT
New features and enhancement
Rakesh Madugula
 
PDF
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
Code red SUM
Shumail Haider
 
I can not get my code to comply it gets mad that I have run declare mo.docx
hamblymarta
 
54240326 (1)
Vinayak Shedgeri
 
54240326 copy
Vinayak Shedgeri
 
COLLECTION IN JAVA PROGRAMMING LANGUAGES
suryae1988
 
Understanding java streams
Shahjahan Samoon
 
Object oriented programming la bmanual jntu
Khurshid Asghar
 
I need help with this code working Create another project and add yo.pdf
fantoosh1
 
Wrapper class
kamal kotecha
 
Nice to meet Kotlin
Jieyi Wu
 
Elementary Sort
Sri Prasanna
 
Java ppt
Rohan Gajre
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
manojmozy
 
Python tour
Tamer Abdul-Radi
 
Java Programs
vvpadhu
 
• GUI design using drag and drop feature of IDE(Net beans), • File IO
SyedShahroseSohail
 
New features and enhancement
Rakesh Madugula
 
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 

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