Java8-Optional

Posted 集美大学 计算机 郑如滨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8-Optional相关的知识,希望对你有一定的参考价值。

传统的对程序中可能出现的null情况进行处理。

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

class Student {
    private String name;

    public String getName() {
        return name;
    }

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

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

}

class Course {// 课程
    private String name;
    private List<Student> stuList;

    public String getName() {
        return name;
    }

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

    public void addStudent(Student... stus) {
        for (Student student : stus) {
            stuList.add(student);
        }
    }

    public Student getStu(int i) {
        return stuList.get(i);
    }

    public List<Student> getStuList() {
        return stuList;
    }

    public Course(String name) {
        this.name = name;
        stuList = new ArrayList<>();
    }

}

public class TestOptional {
    public static void main(String[] args) {
        Course course = new Course("数学");
        Student s0 = new Student("s1");
        Student s1 = new Student(null);
        Student s2 = null;
        course.addStudent(s0, s1, s2);
        int index = 1;//index = 1或2都会抛出NullPointerException
        String name = course.getStuList().get(index).getName();
        System.out.println(name.length());
        
        
    }
    
    private static void testOptional() {
        Course course = new Course("数学");
        Student s0 = new Student("s1");
        Student s1 = new Student(null);
        Student s2 = null;
        course.addStudent(s0, s1, s2);
        int index = 1;//index = 1或2都会抛出NullPointerException
        Student student = course.getStuList().get(1);
        String errorMessage = "";
        String name = "";
        if(student!=null) {
            name = student.getName();
            if(name!=null) {
                System.out.println(name.length());
            }else {
                errorMessage="student对象的name为null";
                
            }
        }else {
            errorMessage="student对象为null";
        }
        System.out.println(name.length());
    }

    private static String findStudent(Course course, int i) {
        Optional<Course> courseNullable = Optional.ofNullable(course);
        String result = courseNullable.map(e -> e.getStu(i)).map(Student::getName).orElse("查询不到");
        return result;
    }
}

以上是关于Java8-Optional的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板

VSCode自定义代码片段6——CSS选择器