Как оптимизировать код вызовом одного метода?

Map<Integer, Meal> currentUserMeals = new HashMap<>();

if (repository.containsKey(userId)) {
currentUserMeals = repository.get(userId);
} else {
repository.put(userId, currentUserMeals);
}

как это можно сделать вызовом одного метода на repository?


Ответы (2 шт):

Автор решения: Komdosh

Это не оптимизация, а сокращение кода:

currentUserMeals = repository.computeIfAbsent(userId, x->new HashMap<Integer, Meal>());

Внутри интерфейса Map определён default метод:

 default V computeIfAbsent(K key,
        Function<? super K, ? extends V> mappingFunction) {
    Objects.requireNonNull(mappingFunction);
    V v;
    if ((v = get(key)) == null) {
        V newValue;
        if ((newValue = mappingFunction.apply(key)) != null) {
            put(key, newValue);
            return newValue;
        }
    }

    return v;
}
→ Ссылка
Автор решения: Alexander Ivanov

Мой вариант:

Map<Integer, Meal> currentUserMeals = repository.get(userId);

if (null == currentUserMeals) {
  currentUserMeals = new HashMap<>();
  repository.put(userId, currentUserMeals);
}
→ Ссылка