【问题标题】:Java 8 - Optional class on List of ObjectsJava 8 - 对象列表上的可选类
【发布时间】:2018-10-31 14:30:14
【问题描述】:

我有一个 ArrayListCar 对象。我正在检查空值和 Germany 并在 if 条件内执行某些操作。

但我想使用Optional 类来避免检查空值。我该如何使用它?

这是我的代码:

public class TestOptional {

    public static List<Car> getCarList() {
        List<Car> carList = new ArrayList<Car>();
        carList.add(new Car("Benz", 2016, "Germany"));
        carList.add(new Car("Rolls Royce", 2015, "Russia"));
        carList.add(new Car("BMW", 2017, null));
        carList.add(new Car("Maruti", 2014, ""));
        return carList;
    }

    public static void main(String args[]) {
        List<Car> carList1=getCarList();
        for(Car c:carList1) {
            if(c.getCountry() != null && c.getCountry().equalsIgnoreCase("Germany")) {
                System.out.println(c.getCarName()+" car is from Germany");
            }
        }

        Optional<Car> optional = getCarList();
    }
}

我收到此错误:

`Type mismatch: cannot convert from List<Car> to Optional<Car>` 

我不确定如何在 List 对象上使用 Optional 类。

请找到我的汽车代码:

public class Car {

    private String carName;
    private int year;
    private String country;

    public Car(String carName, int year, String country) {
        this.carName = carName;
        this.year = year;
        this.country = country;
    }

    public String getCarName() {
        return carName;
    }

    public int getYear() {
        return year;
    }

    public String getCountry() {
        return country;
    }



}

** 更新 1 **

我开始探索一些 Java8 功能,我发现了 Optional 类,我想使用它。我找到了Optional类的用法。

在 Java 8 中,我们在 java.util 包中新引入了一个 Optional 类。引入此类是为了避免我们在代码中不执行 null 检查时经常遇到的 NullPointerException。使用这个类我们可以很容易地检查一个变量是否有空值,通过这样做我们可以避免 NullPointerException。

所以,我尝试为我的 ArrayList 应用 Optional 类,并且我想避免对我的 ArrayList 中的所有对象进行空检查。

List<Car> carList1=getCarList();
    for(Car c:carList1) {
        if(c.getCountry() != null && c.getCountry().equalsIgnoreCase("Germany")) {
            System.out.println(c.getCarName()+" car is from Germany");
        }
    }

在上面的代码中,我检查 Country 对象是否为 null。所以在这里我想避免编写空检查代码(使用可选类)。

【问题讨论】:

  • 一个Optional&lt;Car&gt; 包含零辆或一辆辆汽车。您的列表包含 四辆 辆汽车。 Optional&lt;Car&gt; 应该包含什么?
  • 如果我理解正确,您是否试图避免对country 进行空检查?
  • 您为什么希望 List&lt;Car&gt; 更改为 Optional&lt;Car&gt;?根据您的问题,Car 中的某些内容需要更改(例如,为getCountry() 返回Optional&lt;String&gt;?您还没有将Car 代码放在您的问题中。
  • @Thiru - 是的,我想避免对国家/地区进行空检查
  • 解决这个问题的一个好方法是首先通过将它放在你的构造函数中来使创建具有空国家的汽车成为不可能:this.country = Objects.requireNonNull(country, "Country cannot be null");

标签: java java-8


【解决方案1】:

一般不建议将Optional 与集合一起使用。您可以用空集合完美地表示没有结果。

您真正想要的是更改您的Car 以避免返回null 国家/地区。 所以在你的Car 里面你有String getCountry() 把它改成:

Optional<String> getCountry() {
  return Optional.ofNullable(country);
}

然后在你的循环中你可以这样做:

c.getCountry()
 .filter(country -> country.equalsIgnoreCase("Germany")
 .ifPresent(country -> System.out.println(c.getCarName()+" car is from Germany"));

如果您愿意,也可以使用Stream 来代替for 循环。

getCarList()
       .stream()
       .filter(this::isGerman)
       .forEach(car -> System.out.println(car.getCarName()+" car is from Germany");

函数isGerman()是这样的:

boolean isGerman(Car car) {
  return c.getCountry()
     .filter(country -> country.equalsIgnoreCase("Germany")
     .isPresent();
}

【讨论】:

  • 嗯,这个问题还不是很清楚(你为什么要尝试将汽车列表放入Optional?),做一些研究会让你找到答案。关于如何使用 Java 8 Optional 的文章有数百篇,并不复杂。可能这就是人们投反对票的原因。
  • 我在我的问题中更新了我对Optional 课程的期望。请你给我建议一下。
  • @Karthikeyan 不确定您的问题是什么,您刚刚粘贴了 Javadoc。我在这个答案中向您展示了如何使用它。如果country 有可能是null(有些汽车没有国家?)您不返回String,而是返回Optional&lt;String&gt;Optional 然后提供以功能方式使用它的方法,例如 map()flatMap()filter()ifPresent()
【解决方案2】:

您可以使用类似的方法来检查天气,您的汽车是否符合您的条件。不确定这是否是您要问的。

Optional<Car> carOptional = getCarList()
                           .stream()
                           .filter(Objects::nonNull)
                           .filter(c -> c.getCountry() != null && c.getCountry().equalsIgnoreCase("Germany"))
                           .findFirst();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    相关资源
    最近更新 更多