Labsheets of JavaFullStack
Labsheets of JavaFullStack
}
@FunctionalInterface
interface myinterface2 {
void method2();
}
@FunctionalInterface
interface myinterface3 {
void method3();
}
//partial implementation of interface is not allowed before java8
R3=()->{
System.out.println("Method3 implemented in anonymous class2");
};
R1.method1();
R2.method2();
R3.method3();
Labsheet 2
import java.util.Scanner;
Labsheet 3
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.Collectors;
//LIST INTERFACE METHODS WITH ArrayList (IMPLEMENTED CLASS)
//there are 2 kinds of list to keep objects
//1. generic list to hold objects of primitive types-heterogeneous
//2. specific list to hold objects for both type(primitive and custom)-homogeneous
public class TEST3 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(7);
list.add(15);
list.add(42);
//how to check List created above
//List allows duplicates , preserves the insertion order
System.out.println(list);//possible bcz of toString()
//how to print objects inside the list object
System.out.println("using for-each");
for(Integer i:list) {
System.out.println(i);
}
System.out.println("using iterator");
ListIterator<Integer> itr=list.listIterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
//insert at begin , end and any position
System.out.println(list);
list.add(0,100);
System.out.println(list);
list.add(5,200);
System.out.println(list);
list.add(3,300);
System.out.println(list);
//delete object from list
list.remove(0);
System.out.println(list);
Integer ob = new Integer(200);
list.remove(ob);
System.out.println(list);
//searching an object
ob=new Integer(7);
if( list.contains(ob))
System.out.println("Present");
else
System.out.println("Not Present");
//find index of an object
System.out.println(list.indexOf(ob));
System.out.println("printing few elements......");
//printing few objects from the list
for (int i=0;i<=2;i++) {
System.out.println(list.get(i));
}
//LambdaExpression
oddlist= list.stream().filter(e->e%2!=0).collect(Collectors.toList());
System.out.println("Printing odd list...");
System.out.println(oddlist);
System.out.println(list);
boolean res=list.stream().allMatch(e->e%5==0);
System.out.println(res);
res=list.stream().anyMatch(e->e%5==0);
System.out.println(res);
res=list.stream().noneMatch(e->e%5==0);
System.out.println(res);
Labsheet 4
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;
//binary search
int p=Collections.binarySearch
(studentlist,new Student(342,"upendra",8.3),(x,y)-
>Integer.compare(x.getId(), y.getId()));
System.out.println("is present in the list at "+p+" index");
//binary search returns index of the object from a sorted collection
Student ob1=new Student(101,"amith",7.5);
Student ob2=new Student(100,"nithin",7.8);
Student ob3=new Student(102,"sreekanth",7.4);
Student ob4=new Student(109,"supriya",7.3);
//sort by id
Collections.sort(studentlist,
(x,y)->Integer.compare(y.getId(), x.getId()));
System.out.println("Descending by id"+studentlist);
//sort by name
Collections.sort(studentlist,
(x,y)->y.getName().compareTo(x.getName()));
System.out.println("Descending by name"+studentlist);
//sort by cgpa
Collections.sort(studentlist,
(x,y)->Double.compare(y.getCgpa(), x.getCgpa()));
System.out.println("Descending by cgpa"+studentlist);
// sort using method reference
}
}
TestSpot1
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
class PicnicSpot {
String name;
double distance;
boolean hotelAndRestaurantAvailability;
double reviews;
TestSpot2
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
class Hotel {
private String name;
private double dist_from_location;
private double charges;
private double reviews;
}
class PicnicSpot {
String name;
double distance;
List<Hotel> hotels;
double reviews;
//add constructor with field
public PicnicSpot(String name, double distance, List<Hotel> hotels, double reviews) {
super();
this.name = name;
this.distance = distance;
this.hotels = hotels;
this.reviews = reviews;
}
public PicnicSpot() {
super();
}
// Find the best spot as per distance and find the best hotel
// as per distance
Hotel bestHotelByDistance = picnicSpots.stream()
.min((x,y)->Double.compare(x.getDistance(),y.getDistance())).get()
.getHotels().stream()
.min((x,y)->Double.compare(x.getDist_from_location(), y.getDist_from_location()))
.get();
System.out.println("Best Hotel as per distance: " + bestHotelByDistance);
// Find the best spot as per distance and find the best hotel
// as per price
PicnicSpot best_spot_as_per_distance=
picnicSpots.stream().min((x,y)->Double.compare(x.getDistance(), y.getDistance()))
.get();
System.out.println("Best spot as per distance "+best_spot_as_per_distance);
}
}
Labsheet 5
/*objective - prepare a table of entries
consists of customerid as key and List of product
selected to purchase are values
Define a Product
Map<String, List<Product>>
sunny123--------------> {hp laptop, }
*/
import java.util.*;
//pojo
class Product {
private String prodId;
private String prodName;
private String prodCategory;
private double prodPrice;
// add getter setter, constructor , toString, equals and hashCode
public String getProdId() {
return prodId;
}
public void setProdId(String prodId) {
this.prodId = prodId;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public String getProdCategory() {
return prodCategory;
}
public void setProdCategory(String prodCategory) {
this.prodCategory = prodCategory;
}
public double getProdPrice() {
return prodPrice;
}
public void setProdPrice(double prodPrice) {
this.prodPrice = prodPrice;
}
public Product(String prodId, String prodName, String prodCategory, double prodPrice) {
super();
this.prodId = prodId;
this.prodName = prodName;
this.prodCategory = prodCategory;
this.prodPrice = prodPrice;
}
public Product() {
super();
}
@Override
public String toString() {
return "Product [prodId=" + prodId + ", prodName=" + prodName + ",
prodCategory=" + prodCategory
+ ", prodPrice=" + prodPrice + "]";
}
@Override
public int hashCode() {
return Objects.hash(prodCategory, prodId, prodName, prodPrice);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
return Objects.equals(prodCategory, other.prodCategory) &&
Objects.equals(prodId, other.prodId)
&& Objects.equals(prodName, other.prodName)
&& Double.doubleToLongBits(prodPrice) ==
Double.doubleToLongBits(other.prodPrice);
}
}
public class Test5 {
public static void main(String[] args) {
List<Product> productList1 = new ArrayList<Product>();
productList1.add(new Product("pres101","Java Complete Reference","book",700));
productList1.add(new Product("pres109","Python","snake",1000));
productList1.add(new Product("pres1125","HP Laptop","Electronic",45000));
productList1.add(new Product("pres1199","Iphone","Electronic",150000));
List<Product> productList2 = new ArrayList<Product>();
productList2.add(new Product("pres101","Java Complete Reference","book",700));
productList2.add(new Product("pres1101","water bottles","Acessories",700));
productList2.add(new Product("pres1230","Jeans","Clothes",3000));
productList2.add(new Product("pres1199","Ihone","Electronic",150000));
productList2.add(new Product("pres101","Java Complete Reference","book",700));
List<Product> productList3 = new ArrayList<Product>();
productList3.add(new Product("pres230","Sotalol","medicine",200));
productList3.add(new Product("pres238","Carvedilol","medicine",700));
productList3.add(new Product("pres239","Aciclovir","medicine",70));
productList3.add(new Product("pres245","Pantoprazol","medicine",240));
productList3.add(new Product("pres289","Nitroglyserin","medicine",1000));
Map<String, List<Product>> table =
new HashMap<String,List<Product>>();
table.put("PUNIV00448", productList3);
table.put("PUNIV01690", productList1);
table.put("PUNIV00123", productList2);
//Display the details of table
for(Map.Entry<String,List<Product>> e:table.entrySet()) {
System.out.println(e.getKey()+"->"+e.getValue());
}
//Display the details by name of products
for(Map.Entry<String,List<Product>> e:table.entrySet()) {
System.out.print(e.getKey()+"->");
e.getValue().stream().forEach(x->
System.out.print(x.getProdName()+","));
System.out.println();
}
TestOneToMany
package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.sql.*;
}
class Address {
private String HouseNumber;
private String postOffice;
private String district;
private String state;
private int pin;
private String mobileNumber;
private int sid;
public String getHouseNumber() {
return HouseNumber;
}
public void setHouseNumber(String houseNumber) {
HouseNumber = houseNumber;
}
public String getPostOffice() {
return postOffice;
}
public void setPostOffice(String postOffice) {
this.postOffice = postOffice;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public Address(String houseNumber, String postOffice, String district, String state, int pin,
String mobileNumber,
int sid) {
super();
HouseNumber = houseNumber;
this.postOffice = postOffice;
this.district = district;
this.state = state;
this.pin = pin;
this.mobileNumber = mobileNumber;
this.sid = sid;
}
public Address() {
super();
}
@Override
public String toString() {
return "Address [HouseNumber=" + HouseNumber + ", postOffice=" + postOffice + ",
district=" + district
+ ", state=" + state + ", pin=" + pin + ", mobileNumber=" +
mobileNumber + ", sid=" + sid + "]";
}
@Override
public int hashCode() {
return Objects.hash(HouseNumber, district, mobileNumber, pin, postOffice, sid,
state);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
return Objects.equals(HouseNumber, other.HouseNumber) &&
Objects.equals(district, other.district)
&& Objects.equals(mobileNumber, other.mobileNumber) && pin == other.pin
&& Objects.equals(postOffice, other.postOffice) && sid == other.sid
&& Objects.equals(state, other.state);
}
}
//create a datasource object-singleton
interface StudentDAO {
public boolean create(String dbn,String user,String pwd);
public int insertStudent(Student s);
public int updateStudent(int id, Student s);
public int deleteStudent(int id);
public List<Student> fetchAllStudents();
public Student fetchAStudent(int id);
}
class StudentDAOImpl implements StudentDAO {
private Connection cts=null;
public static StudentDAOImpl ob=null;
public static StudentDAOImpl createObject() {
if(ob==null)
ob=new StudentDAOImpl();
return ob;
}
private StudentDAOImpl() {}
public boolean create(String dbn,String user,String pwd) {
boolean result=true;
try {
cts=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbn,user,pwd);
Class.forName("com.mysql.jdbc.Driver");
Statement st=cts.createStatement();
// result=st.execute("create table student(id int primary key, name varchar(30), cgpa
double)");
}catch(Exception e) {
System.out.println(e);
}
if(result==true) {
return true;
}
else {
return false;
}
}
public int insertStudent(Student s) {
int response=0;
try {
String sql="insert into student values(?,?,?)";
PreparedStatement p=cts.prepareStatement(sql);
p.setInt(1, s.getId());
p.setString(2, s.getName());
p.setDouble(3, s.getCgpa());
response=p.executeUpdate();
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public int updateStudent(int id, Student s) {
int response=0;
try {
String sql="update student set cgpa=? where id=?";
PreparedStatement p=cts.prepareStatement(sql);
p.setDouble(1, s.getCgpa());
p.setInt(2, s.getId());
response=p.executeUpdate();
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public int deleteStudent(int id) {
int response=0;
try {
String sql="delete from student where id=?";
PreparedStatement p=cts.prepareStatement(sql);
p.setInt(1, id);
response=p.executeUpdate();
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public List<Student> fetchAllStudents(){
List<Student> response=new ArrayList<Student>();
try {
String sql="select * from student";
PreparedStatement p=cts.prepareStatement(sql);
ResultSet r=p.executeQuery();
Student s;
while(r.next()) {
s=new Student();
s.setId(r.getInt(1));
s.setName(r.getString(2));
s.setCgpa(r.getDouble(3));
System.out.println(s.getId());
response.add(s);
}
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public Student fetchAStudent(int id) {
return null;
}
}
interface AddressDAO {
public boolean create(String dbn,String user,String pwd);
public int insertAddress(Address s);
public int updateAddress(String hn, Address s);
public int deleteAddress(String hn);
public List<Address> fetchAllAddresses();
public Address fetchAAddress(String hn);
}
class AddressDAOImpl implements AddressDAO {
public static AddressDAOImpl ob=null;
private Connection cta=null;
public static AddressDAOImpl createObject() {
if(ob==null)
ob=new AddressDAOImpl();
return ob;
}
private AddressDAOImpl() {}
public boolean create(String dbn,String user,String pwd) {
boolean result=false;
try {
cta=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbn,user,pwd);
Class.forName("com.mysql.jdbc.Driver");
Statement st=cta.createStatement();
String query="create table address(HouseNumber varchar(30) primary key, postofc
varchar(10), district varchar(10), state varchar(10), pin int, mobilenumber varchar(13),sid int, foreign
key(sid) references student(id))";
result=st.execute(query);
}catch(Exception e) {
System.out.println(e);
}
if(result==true) {
return true;
}
else {
return false;
}
}
public int insertAddress(Address s) {
return 1;
}
public int updateAddress(String hn, Address s) {
return 1;
}
public int deleteAddress(String hn) {
return 1;
}
public List<Address> fetchAllAddresses(){
return null;
}
public Address fetchAAddress(String hn) {
return null;
}
}
}
public static int updateStudent(int id,Student s) {
return (ob.updateStudent(id, s));
}
public static int deleteStudent(int id) {
return(ob.deleteStudent(id));
}
public static List<Student> fetchAllStudent() {
return (ob.fetchAllStudents());
}
}while(repeat!='n');