Home > Software design >  Java - Enumeration as Optional
Java - Enumeration as Optional

Time:11-23

My program works if I initialize my Enum Cities as null but I want it to be Optional. I can make it Optional but then the class Address which is supposed to take Cities as one of it's parameters won't do so because Cities is not defined as Optional in the class Address but I can't change it so that the Optional is the parameter of this class and that it works

This is my enum class

public enum Cities {

    NEWYORK("New York",10000),
    LOSANGELES("Los Angeles",90000),
    CHICAGO("Chicago",60000),
    NEWORELANS("NEW Orlans",70000),
    DALLAS("Dallas",75000);

    private final String name;
    private final Integer postalCode;

  Cities(String name, Integer postalCode) {
        this.name=name;
        this.postalCode=postalCode;
    }

It works like this

private static Address addressInput (Scanner scanner) {

        ArrayList<Cities> cityList = new ArrayList<>();
        Cities city = null;

        do {
            for (Cities cities : Cities.values()) {
                System.out.println(cities);
                cityList.add(cities);
            }
            String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");

            for (int j = 0; j < cityList.size(); j  ) {
                if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
                    city = cityList.get(j);
                }
            }
            if (city == null) {
                System.out.println("Please select one of the cities on the list.");
            }
        } while (city == null);

        String street = dataInput(scanner, "Name of the street: ");
        String houseNumber = dataInput(scanner, "House number: ");

        return new Address.Builder(city)
                .atStreet(street)
                .atHouseNumber(houseNumber)
                .build();
    }

But Adress constructor now won't accept city if it's Optional because it is defined differently in Adress class


 private static Address addressInput (Scanner scanner) {

        ArrayList<Cities> cityList = new ArrayList<>();
        Optional<Cities> city = Optional.empty();

        do {
            for (Cities cities : Cities.values()) {
                System.out.println(cities);
                cityList.add(cities);
            }
            String cityInput = dataInput(scanner, "Unesite naziv jednog od ponuđenih gradova: ");

            for (int j = 0; j < cityList.size(); j  ) {
                if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
                    city = Optional.ofNullable(cityList.get(j));
                }
            }
            if (city.isEmpty()) {
                System.out.println("Molimo odabrati jedan od ponuđenih gradova.");
            }
        } while (city.isEmpty());

public class Address {

private String street;
private String houseNumber;
private Cities city;

public Address(Cities city,String street, String houseNumber) {
    this.street = street;
    this.houseNumber = houseNumber;
    this.city=city;
}

public static class Builder {
    Cities city;
    String street;
    String houseNumber;

    public Builder (Cities city){
        this.city=city;
    }

    public Builder atStreet (String street){
        this.street=street;
        return this;
    }

    public Builder atHouseNumber (String houseNumber){
        this.houseNumber=houseNumber;
        return this;
    }

    public Address build (){
        Address address = new Address();
        address.city=city;
        address.houseNumber=houseNumber;
        address.street=street;

        return address;
    }

}

How to edit class to accept Optional?

CodePudding user response:

Using Optional here is probably not the best idea as other have mentioned in the comments above, but if you really wish as it's for learning purposes you can do something like this:

    ArrayList<Cities> cityList = new ArrayList<>();
    Optional<Cities> city = Optional.empty();

    do {
        for (Cities cities : Cities.values()) {
            System.out.println(cities);
            cityList.add(cities);
        }
        String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");

        for (int j = 0; j < cityList.size(); j  ) {
            if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
                city = Optional.ofNullable(cityList.get(j));
            }
        }
        if (!city.isPresent()) {
            System.out.println("Please select one of the cities on the list.");
        }
    } while (!city.isPresent());

    String street = dataInput(scanner, "Name of the street: ");
    String houseNumber = dataInput(scanner, "House number: ");

    return new Address.Builder(city.get())
            .atStreet(street)
            .atHouseNumber(houseNumber)
            .build();

By using optionals get() method you'll get it's value immediately but note that it will throw NoSuchElementException if no value is present. Usually it's not recommended to use get() to get Optional's value, but in this case it can be used as you're sure that Optional will be present because of the while condition.

Anyway, when you are not sure if optional is present then it's best to use alternative Optional methods to get it's value:

orElse() - Return the value if present, otherwise return other. orElseGet(Supplier<? extends T> other) - Return the value if present, otherwise invoke other and return the result of that invocation. orElseThrow(Supplier<? extends X> exceptionSupplier) - Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

  • Related