Important java programs(collection+file)

  • 24,061 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
24,061
On Slideshare
0
From Embeds
0
Number of Embeds
50

Actions

Shares
Downloads
112
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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