0% found this document useful (0 votes)
6 views23 pages

Java 8 Functional Interfaces & Lambda

Uploaded by

Sherry Kalkeri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

Java 8 Functional Interfaces & Lambda

Uploaded by

Sherry Kalkeri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Labsheet 1

//JAVA 8 NEW FEATURES


//1. FUNCTIONAL INTERFACE
/* functional interface is an interface that consists exactly one
* abstract method. Unlike interface we can keep n number of abstract
* methods in an interface before java 8.
* Lambda expression is not applicable before java 8 other than
* functional interface
* @FunctionalInterface is used to declare an intterface as functional
* There will be many (apis to be used) open source libraries
* which consists of functional interface instead of interface.
Example Runnable , Clonable, Serializable, ActionListener
These are functional and marker interface
*/

//2. LAMDA EXPRESSION


//3. STREAM METHODS FOR COLLECTION
// create an interface with three methods , refactor it using functional
//interface
@FunctionalInterface
interface myinterface1 {
void method1();

}
@FunctionalInterface
interface myinterface2 {
void method2();

}
@FunctionalInterface
interface myinterface3 {
void method3();

}
//partial implementation of interface is not allowed before java8

public class TEST1 {

public static void main(String[] args) {


// object creation
//polymorphism or loose-coupling approach
myinterface1 R1=()->{
[Link](" method1 implemented in anonymous class1");
};
myinterface2 R2=()->{
[Link](" method2 implemented in anonymous class1");
};
myinterface3 R3=()->{
[Link](" method3 implemented in anonymous class1");
};
R1.method1();
R2.method2();
R3.method3();
R1=()->{
[Link]("Method1 implemented in anonymous class2");
};
R2=()->{
[Link]("Method2 implemented in anonymous class2");
};

R3=()->{
[Link]("Method3 implemented in anonymous class2");
};
R1.method1();
R2.method2();
R3.method3();

Labsheet 2
import [Link];

//create a functional interface shape to implement a method


// area() to print area of circle and square.
//use lambda expression
@FunctionalInterface
interface shape {
void area();
}
public class TEST2 {

public static void main(String[] args) {


shape r = ()->{
int radious;
double a;
Scanner sc = new Scanner([Link]);
[Link]("Enter radious");
radious=[Link]();
a=3.141*radious*radious;
[Link]("area of anonymous circle is "+a);
};
[Link]();
r=()-> {
int side;
double a;
Scanner sc = new Scanner([Link]);
[Link]("Enter side");
side=[Link]();
a=side*side;
[Link]("area of anonymous square is "+a);
};
[Link]();
}

Labsheet 3
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
//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>();
[Link](10);
[Link](7);
[Link](15);
[Link](42);
//how to check List created above
//List allows duplicates , preserves the insertion order
[Link](list);//possible bcz of toString()
//how to print objects inside the list object
[Link]("using for-each");
for(Integer i:list) {
[Link](i);
}
[Link]("using iterator");
ListIterator<Integer> itr=[Link]();
while([Link]()) {
[Link]([Link]());
}
//insert at begin , end and any position
[Link](list);
[Link](0,100);
[Link](list);
[Link](5,200);
[Link](list);
[Link](3,300);
[Link](list);
//delete object from list
[Link](0);
[Link](list);
Integer ob = new Integer(200);
[Link](ob);
[Link](list);
//searching an object
ob=new Integer(7);
if( [Link](ob))
[Link]("Present");
else
[Link]("Not Present");
//find index of an object
[Link]([Link](ob));
[Link]("printing few elements......");
//printing few objects from the list
for (int i=0;i<=2;i++) {
[Link]([Link](i));
}

//soring in default/natural order


//sorting specific-primitive list
[Link](list);
[Link]("After sorting");
[Link](list);
[Link](19);
[Link](24);
[Link](53);
[Link](76);
[Link](list);
//filter only the odd integer objects from the above list
[Link]("printing odd elements");
for(Integer i:list) {
if(i%2!=0)
[Link](i);
}
//create a separate list to hold all odd objects
List<Integer> oddlist=new ArrayList<Integer>();
for(Integer i:list) {
if(i%2!=0)
[Link](i);
}

//LambdaExpression
oddlist= [Link]().filter(e->e%2!=0).collect([Link]());
[Link]("Printing odd list...");
[Link](oddlist);
[Link](list);
boolean res=[Link]().allMatch(e->e%5==0);
[Link](res);
res=[Link]().anyMatch(e->e%5==0);
[Link](res);
res=[Link]().noneMatch(e->e%5==0);
[Link](res);

int greatest=[Link]().max((x,y)->[Link](x, y)).get();


[Link]("Greatest element in the list "+greatest);
int smallest=[Link]().min((x,y)->[Link](x, y)).get();
[Link]("Smallest element in the list "+smallest);
//try with method reference
long count=[Link]().count();
[Link]("No. of objects "+count);
}
}

Labsheet 4
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

//List for custom objects


//pojo-plain old java object (legacy)
//constructor, setter and getter toString()
//equals() and hashCode()
class Student {
private int id;
private String name;
private double cgpa;
//shift alt s
public Student(int id, String name, double cgpa) {
[Link] = id;
[Link] = name;
[Link] = cgpa;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
[Link] = cgpa;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", cgpa=" + cgpa + "]";
}
}

public class TEST4 {


public static void main(String[] args) {
//creating a list of custom student object
List<Student> studentlist=new ArrayList<Student>();
[Link](new Student(389,"rohan",7.8));
[Link](new Student(401,"dileep",8.6));
[Link](new Student(388,"thousif",9.4));
[Link](new Student(342,"upendra",8.3));
[Link](new Student(609,"laxmi",7.9));
[Link](new Student(712,"chandana",7.4));
[Link](new Student(245,"shruthi",8.2));
[Link](new Student(1,"asmita",8.6));
[Link](new Student(75,"madiha",8.8));
[Link](new Student(94,"rajkumar",7.8));
[Link](new Student(742,"thasmay",5.8));
[Link](new Student(729,"pavani",7.9));
[Link](new Student(736,"vamshika",9.4));
[Link](new Student(716,"srihitha",7.8));
[Link](new Student(789,"harshitha",8.3));
//Displaying the list at a time
[Link]("list as one object");
[Link](studentlist);
//Displaying objects present in the list
[Link]("through forEach loop");
for(Student s:studentlist) {
[Link](s);
}
//Displaying through forEach
[Link]("through forEach method");
[Link]()
.forEach(x->[Link](x));
//Displaying through iterator
[Link]("through list iterator");
ListIterator<Student> itr=[Link]();
while([Link]()) {
[Link]([Link]());
}
//insert delete search
[Link](0,new Student(765,"anjaneya",7));
[Link](16,new Student(105,"pavan",7.2));
[Link](10,new Student(749,"priya",8.8));
[Link](studentlist);
[Link](0);
[Link](studentlist);
[Link](new Student(749,"priya",8.8));
[Link](studentlist);
if([Link](new Student(749,"priya",8.8)))
[Link]("is present in the list");
else
[Link]("is not present in the list");

//binary search
int p=[Link]
(studentlist,new Student(342,"upendra",8.3),(x,y)-
>[Link]([Link](), [Link]()));
[Link]("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);

List<Student> secondlist=new ArrayList<Student>();


[Link](ob1);[Link](ob2);[Link](ob3);
[Link]("second list "+secondlist);
[Link](secondlist,(x,y)->[Link]([Link](), [Link]()));
int index=[Link](secondlist, ob4,(x,y)->[Link]([Link](),
[Link]()));//-1-p
[Link](index);
//sort by id
[Link](studentlist,(x,y)->[Link]([Link](), [Link]()));
[Link]("Ascending by id"+studentlist);
//sort by name
[Link](studentlist,
(x,y)->[Link]().compareTo([Link]()));
[Link]("Ascending by name"+studentlist);
//sort by cgpa
[Link](studentlist,
(x,y)->[Link]([Link](), [Link]()));
[Link]("Ascending by cgpa"+studentlist);

//sort by id
[Link](studentlist,
(x,y)->[Link]([Link](), [Link]()));
[Link]("Descending by id"+studentlist);
//sort by name
[Link](studentlist,
(x,y)->[Link]().compareTo([Link]()));
[Link]("Descending by name"+studentlist);
//sort by cgpa
[Link](studentlist,
(x,y)->[Link]([Link](), [Link]()));
[Link]("Descending by cgpa"+studentlist);
// sort using method reference
}
}
TestSpot1
import [Link];
import [Link];
import [Link];
import [Link];

class PicnicSpot {
String name;
double distance;
boolean hotelAndRestaurantAvailability;
double reviews;

public PicnicSpot(String name, double distance, boolean hotelAndRestaurantAvailability, double


reviews) {
[Link] = name;
[Link] = distance;
[Link] = hotelAndRestaurantAvailability;
[Link] = reviews;
}
//add getter and setter

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getDistance() {


return distance;
}

public void setDistance(double distance) {


[Link] = distance;
}

public boolean isHotelAndRestaurantAvailability() {


return hotelAndRestaurantAvailability;
}

public void setHotelAndRestaurantAvailability(boolean hotelAndRestaurantAvailability) {


[Link] = hotelAndRestaurantAvailability;
}

public double getReviews() {


return reviews;
}

public void setReviews(double reviews) {


[Link] = reviews;
}
@Override
public String toString() {
return "PicnicSpot{" +
"name='" + name + '\'' +
", distance=" + distance +
", hotelAndRestaurantAvailability=" + hotelAndRestaurantAvailability +
", reviews=" + reviews +
'}';
}
}

public class PicnicSpotsAnalyzer {


public static void main(String[] args) {
// Creating a List of PicnicSpot objects
List<PicnicSpot> picnicSpots = new ArrayList<>();
[Link](new PicnicSpot("Beach", 10.5, true, 4.2));
[Link](new PicnicSpot("Mountain", 25.0, false, 4.5));
[Link](new PicnicSpot("Park", 5.2, true, 4.0));
[Link](new PicnicSpot("Lake", 15.8, false, 4.8));
[Link](new PicnicSpot("Forest", 30.3, false, 4.1));

// Find the best spot as per distance


PicnicSpot bestSpotByDistance = [Link]()
.min((x,y)->[Link]([Link](),[Link]())).get();
[Link]("Best spot as per distance: " + bestSpotByDistance);

// Find the best spot as per reviews


PicnicSpot bestSpotByReviews = [Link]()
.max((x,y)->[Link]([Link](),[Link]())).get();

[Link]("Best spot as per reviews: " + bestSpotByReviews);

// Find the best spot as per hotel availability


PicnicSpot bestSpotByHotelAvailability = [Link]()
.filter(x->[Link]())
.findFirst()
.orElse(null);
[Link]("Best spot as per hotel availability: " + bestSpotByHotelAvailability);
}
}

TestSpot2
import [Link];
import [Link];
import [Link];
import [Link];
class Hotel {
private String name;
private double dist_from_location;
private double charges;
private double reviews;

public double getReviews() {


return reviews;
}
public void setReviews(double reviews) {
[Link] = reviews;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public double getCharges() {
return charges;
}
public void setCharges(double charges) {
[Link] = charges;
}
public double getDist_from_location() {
return dist_from_location;
}
public void setDist_from_location(double dist_from_location) {
this.dist_from_location = dist_from_location;
}

public Hotel(String name, double dist_from_location, double charges, double reviews) {


super();
[Link] = name;
this.dist_from_location = dist_from_location;
[Link] = charges;
[Link] = reviews;
}
public Hotel() {
super();
}
@Override
public String toString() {
return "Hotel [name=" + name + ", dist_from_location=" + dist_from_location + ",
charges=" + charges
+ ", reviews=" + 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();
[Link] = name;
[Link] = distance;
[Link] = hotels;
[Link] = reviews;
}

public PicnicSpot() {
super();
}

//add getter and setter


public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
[Link] = distance;
}
public List<Hotel> getHotels() {
return hotels;
}
public void setHotels(List<Hotel> hotels) {
[Link] = hotels;
}
public double getReviews() {
return reviews;
}
public void setReviews(double reviews) {
[Link] = reviews;
}
//add toString
@Override
public String toString() {
return "PicnicSpot [name=" + name + ", distance=" + distance + ", hotels=" + hotels +
", reviews=" + reviews
+ "]";
}
}

public class PicnicSpotsAnalyzer {


public static void main(String[] args) {
List<Hotel> hotellist1=new ArrayList<Hotel>();
List<Hotel> hotellist2=new ArrayList<Hotel>();
List<Hotel> hotellist3=new ArrayList<Hotel>();
List<Hotel> hotellist4=new ArrayList<Hotel>();
List<Hotel> hotellist5=new ArrayList<Hotel>();
[Link](new Hotel("Taj",9,5000,4.6));
[Link](new Hotel("Mayfair",7,4500,4.1));
[Link](new Hotel("PalaceVilla",14,3500,3.4));
[Link](new Hotel("Tajmahal",9,5000,4));
[Link](new Hotel("Blue Lagoon",7,4500,5));
[Link](new Hotel("MysoreTemple",14,3500,2.3));
[Link](new Hotel("KingsNight",14,3500,3.5));
[Link](new Hotel("Taj",9,5000,5));
[Link](new Hotel("Mayfair",7,4500,4));
[Link](new Hotel("PalaceVilla",14,3500,2.8));
[Link](new Hotel("Tajmahal",9,5000,4.8));
[Link](new Hotel("Blue Lagoon",7,4500,3.5));
[Link](new Hotel("MysoreTemple",14,3500,4.0));
[Link](new Hotel("KingsNight",14,3500,2));
[Link](new Hotel("PalaceVilla",14,3500,5));
[Link](new Hotel("Tajmahal",9,5000,4));
[Link](new Hotel("Blue Lagoon",7,4500,4.7));
[Link](new Hotel("MysoreTemple",14,3500,3.5));
[Link](new Hotel("KingsNight",14,3500,2.9));

// Creating a List of PicnicSpot objects


List<PicnicSpot> picnicSpots = new ArrayList<PicnicSpot>();
[Link](new PicnicSpot("Beach", 10.5, hotellist1, 4.2));
[Link](new PicnicSpot("Mountain", 25.0, hotellist2, 4.5));
[Link](new PicnicSpot("Park", 5.2, hotellist3, 4.0));
[Link](new PicnicSpot("Lake", 15.8, hotellist4, 4.8));
[Link](new PicnicSpot("Forest", 30.3, hotellist5, 4.1));

// Find the best spot as per distance and find the best hotel
// as per distance
Hotel bestHotelByDistance = [Link]()
.min((x,y)->[Link]([Link](),[Link]())).get()
.getHotels().stream()
.min((x,y)->[Link](x.getDist_from_location(), y.getDist_from_location()))
.get();
[Link]("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=
[Link]().min((x,y)->[Link]([Link](), [Link]()))
.get();
[Link]("Best spot as per distance "+best_spot_as_per_distance);

Hotel best_hotel_as_per_price= best_spot_as_per_distance.getHotels().stream()


.min((x,y)->[Link]([Link](), [Link]())).get();

[Link]("Best hotel as per price "+best_hotel_as_per_price);

// Find the best spot as per reviews


PicnicSpot bestSpotByReviews = [Link]()
.max((x,y)->[Link]([Link](),[Link]())).get();

[Link]("Best spot as per reviews: " + bestSpotByReviews);

// Find the best spot as per hotel availability

}
}

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 [Link].*;
//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) {
[Link] = prodId;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
[Link] = prodName;
}
public String getProdCategory() {
return prodCategory;
}
public void setProdCategory(String prodCategory) {
[Link] = prodCategory;
}
public double getProdPrice() {
return prodPrice;
}
public void setProdPrice(double prodPrice) {
[Link] = prodPrice;
}
public Product(String prodId, String prodName, String prodCategory, double prodPrice) {
super();
[Link] = prodId;
[Link] = prodName;
[Link] = prodCategory;
[Link] = prodPrice;
}
public Product() {
super();
}
@Override
public String toString() {
return "Product [prodId=" + prodId + ", prodName=" + prodName + ",
prodCategory=" + prodCategory
+ ", prodPrice=" + prodPrice + "]";
}
@Override
public int hashCode() {
return [Link](prodCategory, prodId, prodName, prodPrice);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Product other = (Product) obj;
return [Link](prodCategory, [Link]) &&
[Link](prodId, [Link])
&& [Link](prodName, [Link])
&& [Link](prodPrice) ==
[Link]([Link]);
}

}
public class Test5 {
public static void main(String[] args) {
List<Product> productList1 = new ArrayList<Product>();
[Link](new Product("pres101","Java Complete Reference","book",700));
[Link](new Product("pres109","Python","snake",1000));
[Link](new Product("pres1125","HP Laptop","Electronic",45000));
[Link](new Product("pres1199","Iphone","Electronic",150000));
List<Product> productList2 = new ArrayList<Product>();
[Link](new Product("pres101","Java Complete Reference","book",700));
[Link](new Product("pres1101","water bottles","Acessories",700));
[Link](new Product("pres1230","Jeans","Clothes",3000));
[Link](new Product("pres1199","Ihone","Electronic",150000));
[Link](new Product("pres101","Java Complete Reference","book",700));
List<Product> productList3 = new ArrayList<Product>();
[Link](new Product("pres230","Sotalol","medicine",200));
[Link](new Product("pres238","Carvedilol","medicine",700));
[Link](new Product("pres239","Aciclovir","medicine",70));
[Link](new Product("pres245","Pantoprazol","medicine",240));
[Link](new Product("pres289","Nitroglyserin","medicine",1000));
Map<String, List<Product>> table =
new HashMap<String,List<Product>>();
[Link]("PUNIV00448", productList3);
[Link]("PUNIV01690", productList1);
[Link]("PUNIV00123", productList2);
//Display the details of table
for([Link]<String,List<Product>> e:[Link]()) {
[Link]([Link]()+"->"+[Link]());
}
//Display the details by name of products
for([Link]<String,List<Product>> e:[Link]()) {
[Link]([Link]()+"->");
[Link]().stream().forEach(x->
[Link]([Link]()+","));
[Link]();
}

TestOneToMany
package JDBC;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;

/*there are students from section 6cse5 , each students have


atleast 2 addresses , create a database to manage student
address information in MYSQL
*/
//create POJO for student and address
class Student {
private int id;
private String name;
private double cgpa;
// alt shift s
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
[Link] = cgpa;
}
public Student(int id, String name, double cgpa) {
super();
[Link] = id;
[Link] = name;
[Link] = cgpa;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", cgpa=" + cgpa + "]";
}
@Override
public int hashCode() {
return [Link](cgpa, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Student other = (Student) obj;
return [Link](cgpa) == [Link]([Link]) && id ==
[Link]
&& [Link](name, [Link]);
}

}
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) {
[Link] = postOffice;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
[Link] = district;
}
public String getState() {
return state;
}
public void setState(String state) {
[Link] = state;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
[Link] = pin;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
[Link] = mobileNumber;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
[Link] = sid;
}
public Address(String houseNumber, String postOffice, String district, String state, int pin,
String mobileNumber,
int sid) {
super();
HouseNumber = houseNumber;
[Link] = postOffice;
[Link] = district;
[Link] = state;
[Link] = pin;
[Link] = mobileNumber;
[Link] = 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 [Link](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() != [Link]())
return false;
Address other = (Address) obj;
return [Link](HouseNumber, [Link]) &&
[Link](district, [Link])
&& [Link](mobileNumber, [Link]) && pin == [Link]
&& [Link](postOffice, [Link]) && sid == [Link]
&& [Link](state, [Link]);
}

}
//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=[Link](
"jdbc:mysql://localhost:3306/"+dbn,user,pwd);
[Link]("[Link]");
Statement st=[Link]();
// result=[Link]("create table student(id int primary key, name varchar(30), cgpa
double)");

}catch(Exception e) {
[Link](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=[Link](sql);
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
response=[Link]();
}catch(Exception e) {
[Link](e);
}
return response;
}
public int updateStudent(int id, Student s) {
int response=0;
try {
String sql="update student set cgpa=? where id=?";
PreparedStatement p=[Link](sql);
[Link](1, [Link]());
[Link](2, [Link]());
response=[Link]();
}catch(Exception e) {
[Link](e);
}
return response;

}
public int deleteStudent(int id) {
int response=0;
try {
String sql="delete from student where id=?";
PreparedStatement p=[Link](sql);
[Link](1, id);
response=[Link]();
}catch(Exception e) {
[Link](e);
}
return response;
}
public List<Student> fetchAllStudents(){
List<Student> response=new ArrayList<Student>();
try {
String sql="select * from student";
PreparedStatement p=[Link](sql);
ResultSet r=[Link]();
Student s;
while([Link]()) {
s=new Student();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link]());
[Link](s);
}
}catch(Exception e) {
[Link](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=[Link](
"jdbc:mysql://localhost:3306/"+dbn,user,pwd);
[Link]("[Link]");
Statement st=[Link]();
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=[Link](query);

}catch(Exception e) {
[Link](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 class TESTONETOMANY {


static StudentDAOImpl ob=[Link]();
public static int insertStudent(Student s) {
return( [Link](s));

}
public static int updateStudent(int id,Student s) {
return ([Link](id, s));

}
public static int deleteStudent(int id) {
return([Link](id));

}
public static List<Student> fetchAllStudent() {

return ([Link]());
}

public static void main(String[] args) {


[Link]("6cse5", "root", "sunil");
char repeat='y';
int ch=0;
Scanner sc=new Scanner([Link]);
do {
[Link]("Student CRUD.........");
[Link]("Enter choice 1 for insert ");
[Link]("Enter 2 for update");
[Link]("Enter 3 for delete");
[Link]("Enter choice 4 for fetch");
ch=[Link]();
switch(ch) {
case 1:
Student s=new Student();
s=new Student();
[Link]("Enter Id");
int id=[Link]();
[Link]("Enter Name");
String n=[Link]();
[Link]("Enter cgpa");
double c=[Link]();
[Link](id);[Link](n);
[Link](c);
int res= insertStudent(s);
[Link](res+" student inserted");
break;
case 2:
s=new Student();
[Link]("Enter Id");
id=[Link]();
[Link]("Enter Name");
n=[Link]();
[Link]("Enter cgpa");
c=[Link]();
[Link](id);[Link](n);
[Link](c);
res= updateStudent(566,s);
[Link](res+" student updated");
break;
case 3:
[Link]("enter id");
id=[Link]();
res=deleteStudent(id);
[Link](res+" student deleted");
break;
case 4:
List<Student> list=fetchAllStudent();
[Link](list);
break;

}while(repeat!='n');

[Link]("Table student created Sucessfully");


// AddressDAOImpl obb=[Link]();
// res=[Link]("6cse5", "root", "sunil");
//[Link]("Table address created Sucessfully");

Common questions

Powered by AI

Managing student information in a relational database, like MySQL, involves using structured tables, SQL queries, and persistent storage, ensuring data integrity, access control, and concurrency support. It requires setting up database connections and executing queries, as seen in the `StudentDAOImpl` class operations such as `insertStudent()` and `updateStudent()`. In contrast, managing with in-memory Java objects involves using collections like `List<Student>` to store objects, allowing for flexible manipulation and retrieval without persistent storage or SQL overhead but lacks persistence and multi-user concurrency .

Lambda expressions in Java provide a concise way to filter elements in a list using streams. For example, to filter odd numbers from a list, one can use `list.stream().filter(e -> e % 2 != 0).collect(Collectors.toList())`. This creates a stream from the list, applies the filter to keep only odd numbers, and collects the result into a new list. This approach leverages functional programming, enhancing code readability and efficiency .

When designing a `Product` class, encapsulation is achieved by declaring fields as private and providing public getters and setters. This structure ensures control over data access and modification. Encapsulation enables data hiding, thus preventing unauthorized access or alteration. For object comparison, methods like `equals()` and `hashCode()` should be overridden to compare the meaningful properties (e.g., `prodId`, `prodName`). Proper encapsulation and these overrides enable reliable equality checks and hash-based collections usage, like in a `HashMap` .

Method references in Java provide a shorthand for passing methods as arguments, often used in place of lambda expressions to streamline code where the method expression does not require additional input beyond its object. For sorting, a common pattern is to use `ClassName::methodName`, such as with `Collections.sort(list, Student::compareById)`, which is equivalent to a lambda `(x, y) -> x.compareById(y)`. Method references improve readability and reduce verbosity, especially in contexts where an existing method fits the required functional interface .

Creating a map to manage customer-product association in Java involves using `Map<String, List<Product>>` where each customer ID relates to a list of products. For instance, `table.put("customerId", productList)` associates a customer with products they bought. This map allows efficient retrieval and iteration, facilitating management of complex relationships. The `forEach` method can iterate through the map to perform operations or display the data, demonstrating how associative data structures efficiently manage complex real-world relationships .

In Java, to verify the presence of an object in a list, the `contains()` method is used, which returns true if the list contains the specified element. To check the index of the object, the `indexOf()` method is utilized, which returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element .

The 'best' picnic spot from a collection can be determined based on various attributes like distance, reviews, and hotel availability. For distance, the spot with the minimum distance is selected using `picnicSpots.stream().min((x,y) -> Double.compare(x.getDistance(), y.getDistance())).get()`. For reviews, the spot with the maximum reviews is chosen with `picnicSpots.stream().max((x,y)-> Double.compare(x.getReviews(), y.getReviews())).get()`. Considering hotel availability, a filter function identifies spots that meet the requirement .

CRUD operations for a Student object interacting with a MySQL database are implemented in Java using JDBC. The `StudentDAOImpl` class provides methods like `insertStudent()` for Create, executing an SQL `INSERT` statement. `updateStudent()` performs an SQL `UPDATE`, `deleteStudent()` executes a `DELETE` operation, and `fetchAllStudents()` uses `SELECT` to retrieve data. These methods require establishing a connection to the database, preparing SQL statements, and handling the ResultSet. Transaction management and exception handling are crucial to ensure reliable operations .

Sorting custom objects in Java is typically done using the `Collections.sort()` method with a custom `Comparator` to define the sorting logic based on object attributes. For example, sorting by student ID can be achieved using `Collections.sort(list, (x, y) -> Integer.compare(x.getId(), y.getId()))`, and sorting by name can use `Collections.sort(list, (x, y) -> x.getName().compareTo(y.getName()))`. Similarly, sorting by double attributes like CGPA can be done with `Collections.sort(list, (x, y) -> Double.compare(x.getCgpa(), y.getCgpa()))` .

Binary search on a list requires that the list is sorted according to the natural ordering or a specified comparator. In Java, binary search can be performed using `Collections.binarySearch()`, which returns the index of the specified element if it is found, or a negative value if it is not found. When dealing with custom objects, a comparator must define the sorting logic upfront—for example, `Collections.sort(list, (x, y) -> Integer.compare(x.getId(), y.getId()))` to order objects by ID, ensuring binary search operates correctly .

You might also like