简体   繁体   中英

Java 8 - Optional class on List of Objects

I have an ArrayList of Car objects. I'm checking for null values and for Germany and doing something inside an if condition.

But I want to use Optional class to avoid checking for null. How can I use it?

Here is my code:

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();
    }
}

I am getting this error:

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

I am not sure how to use the Optional class on a List of objects.

Please find my Car code :

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;
    }



}

** Update 1 **

I was started exploring some Java8 Features and i found Optional class and i want to use it. I found the usages of Optional class.

In Java 8, we have a newly introduced Optional class in java.util package. This class is introduced to avoid NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException.

So, i tried to apply Optional class for my ArrayList and i want to avoid null checking for all of my objects in my 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");
        }
    }

In the above code, i checking for null for Country Object. So here i want to avoid writting null check code (using Optional Class).

It is generally not recommended to use Optional with collections. You can perfectly represent no results with an empty collection.

What you really want is to change your Car to avoid returning null countries. So inside your Car where you have String getCountry() change it to:

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

Then inside your loop you can do:

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

You can also use a Stream instead of a for loop if you like.

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

Where the function isGerman() is this:

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

You could use something like this to check weather you have a car matching your condition. Not sure if this is what you're asking though.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM