码迷,mamicode.com
首页 > 编程语言 > 详细

Java8-Optional

时间:2018-11-29 19:56:23      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:map   查询   except   sys   对象   array   vat   int   result   

传统的对程序中可能出现的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

标签:map   查询   except   sys   对象   array   vat   int   result   

原文地址:https://www.cnblogs.com/zhrb/p/10040095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!