jdk8中Optional使用

1.首先定義2個實體類,並設置get,set方法java

public class Employee {

    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Company {

    private String name;

    private List<Employee> employeeList;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Employee> getEmployeeList() {
        return employeeList;
    }

    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }
}

2.編寫測試類,杜絕使用傳統方試使用Optional測試

public class OptionalTest {


    public static void main(String[] args) {

        Optional<String> optional = Optional.of("hello");

//        if(optional.isPresent()){
        //傳統方式使用Option
//            System.out.println(optional.get());
//        }

        //推薦Option使用方式
        optional.ifPresent(item-> System.out.println(item));

        Optional<String> optional2 = Optional.empty();
        optional2.ifPresent(item-> System.out.println(item));//爲空就不執行也不報錯


        System.out.println(optional.orElse("world"));
        //爲空就不執行也不報錯

        System.out.println(optional.orElseGet(()->"nihao"));


        Optional<String> optional3 = Optional.ofNullable("hello3");
        optional3.ifPresent(item-> System.out.println(item));
        //返回空集合  不要返回null

    }

}

3.編寫測試類,處理List類型數據this

public class OptionalTest2 {

    public static void main(String[] args) {

        Employee employee = new Employee("zhangsan");
        Employee employee2 = new Employee("lisi");

        Company company = new Company();
        company.setName("company1");//若是註釋該行代碼,系統不會報錯

        List<Employee> list = Arrays.asList(employee,employee2);
        company.setEmployeeList(list);

        Optional<Company> optional = Optional.ofNullable(company);

        System.out.println(optional.map(
                theCompany->theCompany.getEmployeeList()).orElse(Collections.emptyList()));

    }

}
相關文章
相關標籤/搜索