Java - mooc.fi - Exercise 46: Film Reference - method returning a map cannot return null

I do have a method:

public Map<Film, Rating> getPersonalRatings(Person person){

    return this.personalRatings.get(person);
}

So, the basic concept is there's a

HashMap personalRatings <Person, Map<Film, Rating>>

that includes another HashMap of film ratings as map values.

My method needs to return a Map of rated films and so it does. The question is, what should it return if a person never rated a single film and tho the HashMap of film ratings is null. A null cannot be returned.

2 answers

  • answered 2018-01-11 20:03 SurfMan

    Returning null where a collection is expected is not a good practice. Normally, this should be an empty collection. In this case, using Java 8, you can use

    this.personalRatings.getOrDefault(person, Collections.emptyMap());
    

  • answered 2018-01-11 20:03 davidxxx

    To avoid null, you could use the computeIfAbsent() method.

    For example this :

    Map<Film, Rating> ratingByFilmForThisPerson = 
                     personalRatings.computeIfAbsent(person, k -> new HashMap<Film, Rating>());
    

    returns the actual map for the person if a mapping exists.
    Otherwise it creates and associates an empty map for the person.
    In any case it returns the value :