How to return Value after ifPresent Check - java

I am trying to return empName if its present Or else Empty String
But i am unable to return .
After ifPresent its not allowing me to return value , please help need with the syntax .
This is my Structure
import java.util.List;
public class EmployeeData {
private List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
This is my Employee class
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Test Program
import java.util.Collections;
import java.util.Optional;
public class Test {
public static void main(String args[]) {
EmployeeData empData = new EmployeeData();
}
public String getEmpName(EmployeeData empData)
{
Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().findFirst().ifPresent(
return emp->emp.getName();
)).orElse{
return "";
}
}
}

If you want any name of one of the employees you need to map to their name, then use findFirst and orElse.
The ifPresent is to consume the data and only if their is a data : here you want to return and do something if not present
public String getEmpName(EmployeeData empData) {
return Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().filter(Objects::nonNull)
.map(Employee::getName).findFirst().orElse("");
}

Related

Spring Boot Patient Application

an image of code for some reason
I am trying to have a little API run. Everything runs fine but I have to make an addition and am confused. I have to have it so in the URL when I type "localhost:8080/api/v1/{illness}" it will display the names of the people with that illness...help. I have included the two classes that I have. I didn't include my patient class. It's just the constructors and getters/setters for name, gender, illness, and id. I also didn't include the main well because its not needed
package com.sw409.Patientdemo.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.sw409.Patientdemo.model.Patient;
import com.sw409.Patientdemo.service.PatientService;
#RestController
public class PatientController {
PatientService patService = new PatientService();
// CREATE
#PostMapping("api/v1/patients")
public Patient addPatient(#RequestBody Patient p) {
return patService.addPatient(p);
}
//GET ILLNESS (HELP!!!!!!!!!!!!!!!!!!!!!!!)
#PostMapping("api/v1/patients/{illness}")
public void patientIllness() {
return patService.patientIllness(name, illness)
}
// READ
#GetMapping("api/v1/patients")
public List<Patient> getPatient() {
return patService.getPatients();
}
// UPDATE
#PatchMapping("api/v1/patient/{patid}")
public void updatePatient(#PathVariable("patid") Integer id, #RequestBody Patient p) {
patService.updatePatient(id, p);
}
// DELETE
#DeleteMapping("api/v1/patient/{patid}")
public void deletePatient(#PathVariable("patid") Integer id) {
patService.deletePatient(id);
}
}
package com.sw409.Patientdemo.service;
import java.util.*;
import com.sw409.Patientdemo.model.Patient;
public class PatientService {
List<Patient> patientList = new ArrayList<>();
// Create
public Patient addPatient(Patient pat) {
patientList.add(pat);
return pat;
}
public List<Patient> getPatients() {
return patientList;
}
//(HELPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP)
public void patientIllness(String illness) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).equals(illness){
}
}
}
public void updatePatient(Integer id, Patient p) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getId().equals(id)) {
patientList.set(i, p);
}
}
}
public void deletePatient(Integer id) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getId().equals(id)) {
patientList.remove(i);
}
}
}
}
package com.sw409.Patientdemo.model;
public class Patient {
String name;
Integer id;
String gender;
String illness;
public Patient(String name, Integer id, String gender, String illness) {
super();
this.name = name;
this.id = id;
this.gender = gender;
this.illness = illness;
}
public Patient() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIllness() {
return illness;
}
public void setIllness(String illness) {
this.illness = illness;
}
}
Controller
In case you want to get the value of something you should use GET instead of POST because POST use for creating or saving something
Your code:
#PostMapping("api/v1/patients/{illness}")
public void patientIllness() {
return patService.patientIllness(name, illness)
}
The parameter is missing patientIllness() that's why it cannot pass the value to service
The return type is void so you still cannot get anything
Suggestion:
#GetMapping("api/v1/patients/{illness}")
public List<Patient> patientIllness(#PathVariable String illness) {
return patService.patientIllness(illness);
}
Add paramiter in patientIllness(String illness) and you use it with path param so it will be patientIllness(#PathVariable String illness)
The return type should be something that you want to know if you want to know the List of Patients, return should be List<Patient>
Service
Your code:
public void patientIllness(String illness) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).equals(illness){
}
}
}
The return type is void so you have change it if you want to return something to controller
It's worng in this code patientList.get(i).equals(illness) Type of patientList.get(i) is Patient and you compare it with String
Suggestion1:
public List<Patient> patientIllness(String illness) {
List<Patient> result = new ArrayList<>();
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getIllness().equals(illness)) {
result.add(patientList.get(i));
}
}
return result;
}
The return type will be List<Patient>
You should compare with the same type patientList.get(i).getIllness().equals(illness)
Suggestion2: you can change to for each
public List<Patient> patientIllness(String illness) {
List<Patient> result = new ArrayList<>();
for (Patient patient : patientList) {
if (patient.getIllness().equals(illness)) {
result.add(patient);
}
}
return result;
}
Suggestion3: You can change it to use steam, filter, and collect it to list
public List<Patient> patientIllness(String illness) {
return patientList.stream()
.filter(patient -> patient.getIllness().equals(illness))
.collect(Collectors.toList());
}
First of all you need to change your controller function to something like this:
#PostMapping("api/v1/patients/{illness}")
public List<Patient> patientIllness(#PathVariable String illness) {
return patService.patientIllness(illness)
}
I don't understand why you called your service function with two arguments, because it can accept only one. You also need to make this function return list of patients instead of void. And illness is just a path variable, you use it in different functions, so you should understand it. And in your patient service you just need to use filter function, so it will look similiar to this:
public List<Patient> patientIllness(String illness) {
return patientList.stream().filter(patient->patient.getIllness().equals(illness)).collect(Collectors.toList());
}
patientIllness in Controller needs a parameter illness to accept illness path variable from URL.
Also name variable is not initialised (which is provided to service layer, but not used in service layer). So the name parameter can be removed.
Request mapping should be GET to retrieve data - recommended.
patientIllness in Controller should return a List<Patient> as received from service layer.

get the return value of the method which is from Generic class in java

I created a parent class Repo which has methods for insert, delete, display and delete objects in a list. Repo is a generic class. I created a child classes for Repo (like DepartmentRepo class)and pass Department, Employee, etc.. classes. I want perform insert, delete, display and delete operations on any class objects that passed to Repo class.
I need to get the return value of the method "get" which is from Generic class in java. I can only get the method name from Generic here I mention the code files
public class Department {
private long Id;
private String Name;
private String Location;
public Department() {
}
public Department(long id, String name, String location) {
super();
Id = id;
Name = name;
Location = location;
}
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
import java.util.ArrayList;
import java.util.List;
public class Repo<T, U> {
List<T> list = new ArrayList<T>();
public List<T> getAll() {
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) throws NoSuchMethodException, SecurityException {
for (T ele : list) {
if (ele.getClass().getMethod("getId") == id) {
return ele;
}
}
return null;
}
public void delete(U id) throws NoSuchMethodException, SecurityException {
list.remove(get(id));
}
}
public class DepartmentRepo extends Repo<Department, Long>{
}
class MainApi
{
public static void main (String[] args)
{
DepartmentRepo dept = new DepartmentRepo ();
Department ict=new Department(10001,"Dept of ICT","Town");
Department cs=new Department(10002,"Dept of Computer Science","Pampaimadu");
Department bio=new Department(10003,"Dept of Bio Science","Pampaimadu");
Department sats=new Department(10004,"Dept of Statistics","Kurumankadu");
dept.insert(ict);
dept.insert(cs);
dept.insert(bio);
dept.insert(sats);
System.out.println();
dept.getAll();
try{
dept.get(10001);
}
catch(Exception e){
}
}
}
As another solution, and an answer to your comment, you could use elements inheritance, and avoid reflection calls and exceptions.
1- Create an element interface OR class
public interface RepoElement<U> {
U getId();
}
OR
public class RepoElement<U> {
private U Id;
public RepoElement() {}
public RepoElement(U id) {
Id = id;
}
public U getId() {
return Id;
}
public void setId(U id) {
Id = id;
}
}
2- Make Department inherit from the interface OR class
public class Department implements RepoElement<Long> {
(...)
public Long getId() {
return Id;
}
(...)
}
OR
public class Department extends RepoElement<Long> {
private String Name;
private String Location;
public Department() {
super();
}
public Department(long id, String name, String location) {
super(id);
Name = name;
Location = location;
}
}
3- Use it directly in the Repo class (and remove exceptions)
public class Repo<T extends RepoElement<U>, U> {
(...)
public T get(U id) {
for (T ele : list) {
if (ele.getId().equals(id)) {
return ele;
}
}
return null;
}
public void delete(U id) {
list.remove(get(id));
}
(...)
}
As a last suggestion, you could use a Map instead of a List in the Repo class, and get rid of any search complexity/optimizations:
public class Repo<T extends RepoElement<U>, U> {
Map<U, T> map = new HashMap<U, T>();
public Collection<T> getAll() {
return map.values();
}
public void insert(T obj) {
map.put(obj.getId(), obj);
}
public T get(U id) {
return map.get(id);
}
public void delete(U id) {
map.remove(id);
}
}
You need to invoke the getId() method so that it will return the id to perform comparison correctly:
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
public class Repo<T, U> {
List<T> list = new ArrayList<T>();
public List<T> getAll() {
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
for (T ele : list) {
if (ele.getClass().getMethod("getId").invoke(ele).equals(id)) {
return ele;
}
}
return null;
}
public void delete(U id) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
list.remove(get(id));
}
}

Replace lambda with method reference containing new keyword

List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());
How to replace this (inv -> new Employee(inv)) lambda with Method reference.
Full Code reference:
package org.learn.copy;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DeepCopy {
public static void main(String[] args){
Employee emp = new Employee();
emp.setName("Hello");
emp.setRollNumber("12345");
Employee emp1 = new Employee();
emp1.setName("Hi");
emp1.setRollNumber("123456");
List<Employee> empList = new ArrayList<>();
empList.add(emp);
empList.add(emp1);
List<Employee> empListRef = empList;
System.out.println("empList Obj: "+empList.get(0).getName());
System.out.println("empListRef Obj: "+empListRef.get(0).getName());
List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());
empListObjDeepCopy.get(0).setName("Hi");
System.out.println("empList Obj: "+empList.get(0).getName());
System.out.println("empListRef Obj: "+empListRef.get(0).getName());
System.out.println("empListObjDeepCopy Obj: "+empListObjDeepCopy.get(0).getName());
}
}
class Employee {
private String name;
private String rollNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
public Employee(Employee employee) {
this.name = employee.name;
this.rollNumber = employee.rollNumber;
}
public Employee() {
super();
}
}
Using .map(Employee::new) is ambiguous because you have two constructors in your Employee class. Try to leave only one.

Adding elements to an ArrayList from another class

I just have this basic code where I need help adding employee data to an ArrayList of another class. I am just writing this code in preparation for an assignment, so don't bash my code too much. Essentially though, i'll be needing to add elements of employees and delete them eventually. But for now, I just need help adding the elements to my other Employee class. =]
public class main {
private static Employee employee;
public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
...............
import java.util.ArrayList;
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
}
Simple Example -
package com;
import java.util.ArrayList;
public class TestPage{
public static void main(String[] args){
Employee emp1, emp2;
emp1 = new Employee();
emp2 = new Employee();
emp1.setName("MAK");
emp2.setName("MICHELE");
emp1.setAddress("NY");
emp2.setAddress("WY");
//and keep putting other information like this
ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);
System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());
System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}
class Employee{
String name, address;
int age, salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
It seems like what you're asking is based on one employee having sub-employees and that structurally that probably represents a hierarchy (Some commenters seem to be missing that point). But that's an assumption on my part. Based on that assumption.
A little bit of feedback to start on structure of your main class:
public class main {
public static void main(String[] args) {
Employee employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
It seems to me that there's no reason to have a static instance variable for that root employee instance. You should try to limit the scope of variables where possible. It seems like it could very well be in the main() method's scope.
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> employees= new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
It may be better to name your arraylist employees or employeeList. I went with employees in this case because that convention is preferable.
And in relation to your question, ArrayList is pass by reference so you could just add a getter method for the sub-employee list (employees).
To add employees from your main method you could do something like
Employee rootEmployee = new Employee(5, 10.0);
rootEmployee.getEmployees().add(new Employee(6, 5.0));
Or you could add an additional method to Employee like this:
public void addEmployee(Employee e) {
employees.add(e);
}

db4o - weird characters when retrieving objects

import java.io.File;
import com.db4o.Db4o;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;
public class Student {
private String name;
public AlumnoBDOO(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ObjectContainer bd = Db4oEmbedded.openFile("students.db4o");
try {
Student s1 = new Student("Carl");
bd.store(s1)
showStudents(bd);
} catch (Exception e) {
e.printStackTrace();
} finally {
bd.close();
}
}
public static void showResult(ObjectSet rs){
System.out.println("Retrieved "+rs.size()+" objects");
while(rs.hasNext()){
System.out.println(rs.next());
}
}
public static void showStudents(ObjectContainer bd){
Query query = bd.query();
query.constrain(Student.class);
query.descend("name");
ObjectSet rs = query.execute();
showResult(rs);
}
}
I just simply want to store a Student in the db4o database but when I want to retrieve all of them it outputs like this:
Student#61070a02
I'm using Eclipse Juno and db40 v.8.0 which I already added as external jar.
Why am I getting those weird characters instead of "Carl"?
That is not weired, but the default implementation of the toString() method. To get meaningfull information you should override this method in your Student class.

Categories