Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Created October 12, 2016 11:47
Show Gist options
  • Select an option

  • Save mhewedy/a39cb2e4eb02ed463dfc2cecf4325454 to your computer and use it in GitHub Desktop.

Select an option

Save mhewedy/a39cb2e4eb02ed463dfc2cecf4325454 to your computer and use it in GitHub Desktop.
java util Optional
public static void main(String[] args) {
System.out.println(getEmployeeNames(simulateWsResult1()));
System.out.println(getEmployeeNames(simulateWsResult2()));
System.out.println(getEmployeeNames(simulateWsResult3()));
System.out.println(getEmployeeNames(simulateWsResult4()));
}
static class Result {
Departement departement;
}
static class Departement{
List<Employee> employees;
}
static class Employee{
String name;
}
static List<String> getEmployeeNames(Result r){
return
Optional.ofNullable(r)
.map(result -> result.departement)
.map(dept -> dept.employees)
.map(empList -> empList.stream())
.map(empStream -> empStream.filter(e -> e.name != null).map(e -> e.name))
.orElse(Stream.empty())
.collect(Collectors.toList());
}
static Result simulateWsResult1() {
Employee e1 = new Employee();
e1.name = "Ali";
Employee e2 = new Employee();
e2.name = "Muhammad";
Departement dept = new Departement();
dept.employees = Arrays.asList(e1, e2);
Result result = new Result();
result.departement = dept;
return result;
}
static Result simulateWsResult2() {
Employee e1 = new Employee();
Employee e2 = new Employee();
Departement dept = new Departement();
dept.employees = Arrays.asList(e1, e2);
Result result = new Result();
result.departement = dept;
return result;
}
static Result simulateWsResult3() {
Departement dept = new Departement();
Result result = new Result();
result.departement = dept;
return result;
}
static Result simulateWsResult4() {
Result result = new Result();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment