【问题标题】:How to acess the variables of type Optional<Some_Type> in java?如何在 java 中访问 Optional<Some_Type> 类型的变量?
【发布时间】:2021-06-17 17:40:27
【问题描述】:

我的主班中有一个学生班。学生类包含一个 ID 和名称。在我的主要课程中,我将 3 名学生添加到列表中。现在我需要获取第一个名字不应该为空的学生。为此,我使用了 java stream() 类,其中包含 findFirst() 方法来获取第一个匹配值。所以返回类型是Optional

这是我写的

Optional<Student> ans = l.stream()
                        .filter(e -> e != null && e.name != null)
                        .findFirst();

我也可以这样写

Student ans = l.stream()
               .filter(e -> e != null && e.name != null)
               .findFirst()
               .orElse(null);

但我不想有 orElse(null)

我的完整代码:

import java.util.*;
import java.io.*;

public class Sample {

public static class Student { 
    int id;
    String name;
}

    public static void main(String args[]) {
        List<Student> l = new ArrayList<>();
        Student s = new Student();
        s.id = 0;
        s.name  = "First";

        Student t = new Student();
        t.id = 1;
        t.name = "";

        Student r = new Student();
        r.id = 2;
        r.name = "Hdyun";

        l.add(s);
        l.add(t);
        l.add(r);

        Optional<Student> ans = l.stream()
                        .filter(e -> e != null && e.name != null)
                        .findFirst();
        System.out.println(ans.name);
    }
}

最后,当我打印名字时,我遇到了以下错误:

Sample.java:32: error: cannot find symbol
        System.out.println(ans.name);
                              ^
  symbol:   variable name
  location: variable ans of type Optional<Student>

我该如何纠正它?

【问题讨论】:

标签: java


【解决方案1】:

您的变量 ans 可能为空;如果您想在值存在的情况下执行某些操作,您可以执行以下操作:

ans.ifPresent(student-> System.out.println(student.name));

【讨论】:

    【解决方案2】:

    Optional 的主要意义是强制处理可空值。 这意味着集合中的所有元素可能与您的条件不匹配,因此当您调用 findFirst() 时,它可能会返回空 Optional。

    如果您确定该集合始终包含必要的元素,则可以使用 .ifPresent(...)orElseThrow

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2020-06-28
      • 2012-02-04
      • 1970-01-01
      相关资源
      最近更新 更多