Java Code Snippets: Database, Lambda, and String Operations
Database URL: jdbc:mysql://mis-sql.uhcl.edu/agarwaln8497
agarwaln8497
1005681
String errorMsg = "";
Connection c = null;
Statement s = null;
ResultSet rset = null;
Submit Method
This method handles database connection and data retrieval.
public String Submit() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver is ok.");
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
c = DriverManager.getConnection(DB_Url, dbusername, password);
s = c.createStatement();
/*String Query1 = "insert into practice (rollNumber,studName,Date,username,pwd,email,phone) "
+ "values('1','" + this.studName + "','1234','" + this.username + "','" + this.pwd + "','" + this.email + "','123')";
s.executeUpdate(Query1);*/
/*String Query1 = "select * from practice";
Student st;
ArrayList<Student> arr = new ArrayList<Student>();
rset = s.executeQuery(Query1);
while (rset.next()) {
st = new Student();
st.rollNumber = rset.getInt(1);
st.studName = rset.getString(2);
arr.add(st);
System.out.println("Success");
}
for(int i=0;i<arr.size();i++){
System.out.println(arr.get(i).rollNumber + " " + arr.get(i).studName);
}*/
} catch (SQLException e) {
errorMsg = e.getMessage();
} finally {
try {
//rset.close();
s.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return "Log";
}
HotelApp hp;
ArrayList<HotelApp> arr = new ArrayList<HotelApp>();
HotelRooms hr;
ArrayList<HotelRooms> roomsarr = new ArrayList<HotelRooms>();
Hotel Data Retrieval
This section retrieves hotel and room data from the database.
try {
c = DriverManager.getConnection(DB_Url, dbusername, password);
s = c.createStatement();
String Query1 = "select * from hotel";
rset = s.executeQuery(Query1);
while (rset.next()) {
hp = new HotelApp();
hp.HotelId = rset.getInt(1);
hp.HotelName = rset.getString(2);
System.out.println(rset.getInt(1));
System.out.println(rset.getString(2));
arr.add(hp);
}
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).HotelName.equals(this.HotelName)) {
String Query2 = "select * from hotelroom where hotelId='" + arr.get(i).HotelId + "' and status='Available'";
rset = s.executeQuery(Query2);
while (rset.next()) {
hr = new HotelRooms();
hr.setHotelId(rset.getInt(1));
hr.setRoomId(rset.getInt(2));
hr.setStatus(rset.getString(3));
System.out.println(rset.getInt(1));
System.out.println(rset.getInt(2));
System.out.println(rset.getString(3));
roomsarr.add(hr);
}
}
}
} catch (SQLException e) {
errorMsg = e.getMessage();
} finally {
try {
if (rset != null) rset.close();
if (s != null) s.close();
if (c != null) c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Lambda Expressions and Streams
Examples of using lambda expressions and streams for data processing.
int val = {1,2,3,4}
sopf("%d",IntStream.of(val).count/min/max())
sopf("%d",IntStream.of(val).average.getAsDouble())
sopf("%d",IntStream.of(val).reduce(1,(x,y)->x+y*y)
sopf("%d",IntStream.of(val).filter(x->x%2==0).map(x->x*10).sorted().forEach(System.out::println)
sopf("%d",Instream.rangeclosed(0,10).sum())
Integer[] val= {1,2,3,4,5,6};
SOPF("%s",Arrays.asList(val));
SOPF("Sorted values: %s",Arrays.stream(val).sorted().collect(Collectors.toList()));
List<Integer> great4= Arrays.stream(val).filter(x->x>4).sorted().collect(Collectors.toList());
SOPF("%s",great4);
String[] str={"Red","yellow","orange"};
SOPF("%s",Arrays.asList(str));
SOPF("%s",Arrays.stream(str).map(String::toUpperCase).collect(Collectors.toList()));
SOPF("%s",Arrays.stream(str).filter(s->s.compareToIgnoreCase("n")<0).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList()));
Employee Data Processing
Examples of using streams to process employee data.
Emp[] e = {
new Emp("Alice","Edward",18,50000),
new Emp("Alice","Jones",18,2000),
new Emp("Alice","Edward",18,300)
};
List<Emp> EList = Arrays.asList(e);
EList.stream().forEach(System.out::println);
Predicate<Emp> condition = x->(x.getSalary() > 1000 && x.getSalary() < 51000);
EList.stream().filter(condition).sorted(Comparator.comparing(Emp::getSalary)).forEach(System.out::println);
SOPF("%s",EList.stream().filter(condition).sorted(Comparator.comparing(Emp::getSalary)).findFirst().get());
EList.stream().map(Emp::getLastName).distinct().forEach(System.out::println);
EList.stream().map(Emp::getName).forEach(System.out::println);
SOPF("%s",EList.stream().mapToDouble(Emp::getSalary).sum());
SOPF("%s",EList.stream().mapToDouble(Emp::getSalary).reduce(0, (x,y) -> x+y));
SOPF("%s",EList.stream().mapToDouble(Emp::getSalary).average().getAsDouble());
Text Processing with Streams
Examples of using streams to process text data.
Pattern pattern = Pattern.compile("\\s+");
Map<String,Long> wordCounts = Files.lines(Paths.get("abc.txt")).map(line->line.replaceAll("(?!')\\p{P}", "")).flatMap(line->pattern.splitAsStream(line)).collect(Collectors.groupingBy(String::toLowerCase,TreeMap::new,Collectors.counting()));
wordCounts.entrySet().stream().collect(Collectors.groupingBy(entry->entry.getKey().charAt(0),TreeMap::new,Collectors.toList())).forEach(letter,wordList)->{SOPF("%C",letter);
wordList.stream().forEach(word->SOPF("%13s:%d",word.getKey(),word.getValue()));{);
Random Number Generation
Example of generating random numbers using SecureRandom.
SecureRandom random = new SecureRandom();
SOPF("%-6s%s%n","Face","Freq");
random.ints(6_000_000,1,7).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).forEach((face,freq)->SOPF("%-6d%d%n",face,freq));
Date Formatting and Parsing
Examples of formatting and parsing dates.
try {
String startDateString = "07/30/2016";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = df.parse(startDateString);
System.out.println("Date, with the default formatting: " + startDate);
Date today = new Date();
System.out.println("today is: " + today);
if (today.after(startDate)) {
System.out.println("success");
} else {
System.out.println("fail");
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat f= new SimpleDateFormat("MM/dd/yyyy");
String s="03/27/1991";
Date d= f.parse(s);
String out=f.format(d);
System.out.println(out);
return base.replaceAll("(?i)" + remove, "");
ArrayList<Integer> arr= new ArrayList<Integer>();
arr.addAll(Arrays.asList(1,17,5,10,13,15,10,5,16,8));
Unique Digits Count
Algorithm to count numbers with unique digits.
public class Solution {
public int countNumbersWithUniqueDigits(int n) {
int[] count = new int[11];
count[0] = 1;
count[1] = 10;
int max = (n > 10) ? 10 : n;
int temp = 9;
for (int i = 2; i <= max; i++) {
temp = temp * (11 - i);
count[i] = count[i - 1] + temp;
}
return count[max];
}
}
String Multiplication
Algorithm to multiply two strings representing numbers.
public String multiply(String num1, String num2) {
String n1 = new StringBuilder(num1).reverse().toString();
String n2 = new StringBuilder(num2).reverse().toString();
int[] d = new int[num1.length()+num2.length()];
for(int i=0; i<n1.length(); i++){
for(int j=0; j<n2.length(); j++){
d[i+j] += (n1.charAt(i)-'0') * (n2.charAt(j)-'0');
}
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<d.length; i++){
int mod = d[i]%10;
int carry = d[i]/10;
if(i+1<d.length){
d[i+1] += carry;
}
sb.insert(0, mod);
}
while(sb.charAt(0) == '0' && sb.length()> 1){
sb.deleteCharAt(0);
}
return sb.toString();
}
Comparator Examples
Examples of using comparators for sorting.
Function<Emp, String> byFirstName = Emp::getFirstName;
Function<Emp, String> byLastName = Emp::getLastName;
Comparator<Emp> lastThenFirst = Comparator.comparing(byLastName).thenComparing(byFirstName);
EList.stream().sorted(lastThenFirst).forEach(System.out::println);
Grouping Employees by Department
Examples of grouping employees by department.
Map<String,List<Emp>> grpbydept = EList.stream().collect(Collectors.groupingBy(Emp::getDept));
grpbydept.forEach((Dept,empInDept)->{
System.out.println(Dept);
empInDept.forEach(em->SOPF("%s",em));});
Counting Employees per Department
Examples of counting employees in each department.
Map<String,Long> cntbyDept = EList.stream().collect(Collectors.groupingBy(Emp::getDept,Collectors.counting()));
cntbyDept.forEach((Dept, count) -> SOPF("%s%d",Dept,count));