How to return Value after ifPresent Check

Tags:



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 "";            
                   }
    }

}

Answer

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("");
}


Source: stackoverflow