Home > Software design >  How to create a hashmap that contains optional and when retreiving it gives me the value or Optional
How to create a hashmap that contains optional and when retreiving it gives me the value or Optional

Time:11-11

How to create a hashmap that contains optional and when retreiving it gives me the value or Optional.empty? However, I am not allowed to check for null, Optional.empty() or use isPresent(), isEmpty(), get().

For Optional<V> get, .get() would either give me null or Optional value but what I want is Optional.empty() or Optional value as I would need to chain these optional together later.

For example, .get("John").flatMap(x -> x.get("ModName")).flatMap(x -> x.get("TestName")).map(Assessment::getGrade). If "John" does not exist in the first map then .get("John") will give me a null and if I use .flatMap(x -> x.get("ModName")), I would get a null pointer exception.

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

class CustomMap<V> {
    private final Map<String, Optional<V>> map;

    public CustomMap() {
        map = new HashMap<String, Optional<V>>();
    }

    public Optional<V> get(String key) {
        return map.get(key);
    }

    public int size() {
        return map.size();
    }

    public CustomMap<V> put(V item) {
        map.put(item.getKey(), Optional.ofNullable(item));
        return this;
    }

CodePudding user response:

You could write a check in your get method, like this:

public Optional<V> get(String key) {
    if (map.contains(key)) {
        return map.get(key);
    } else {
        return Optional.empty();
    }
}
  • Related