返回 Optional<Student> 或 Optional.empty()

Returning Optional<Student> or Optional.empty()

我正在尝试使用 Optional 来了解它是如何工作的。假设我有这个 class:

public class Student {
    private int id;
    private String name;

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

并且我想 return 通过 Id 找到一个学生,或者 Optional.empty 如果没有找到它。这是我目前所拥有的:

public class Main {
    static List<Student> students = new ArrayList<>();

    public static void main(String[] args) {
        students.add(new Student(1, "name1"));
        students.add(new Student(2, "name2"));
        students.add(new Student(3, "name3"));

        System.out.println(getStudentById(1).get().getName());
    }

    public static Optional<Student> getStudentById(int id) {
        return students
                .stream()
                .filter( s -> s.getId() == id)
                .findFirst();
    }
}

可行,但我想添加这一行:

.findFirst()
.orElse(Optional.empty());

我得到了这个: 错误:(23, 39) java:类型不兼容:不存在类型变量 T 的实例,因此 java.util.Optional 符合 com.company.Student

另外我想知道这是否是遍历列表的正确方法,我的意思是逐个元素还是有更好的方法?

如果你阅读 Stream#findFirst() 的 javadocs 你会发现你已经拥有了你需要的东西:

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

那就这样吧

return students
            .stream()
            .filter( s -> s.getId() == id)
            .findFirst();