What are best practices related to checking if the Map contains an element since Java 8? I want to check if the Map contains an element and based on it get the object or create a new one and put it into the map. The functional way seems to be too verbose.
final private static Map<Integer, BowlingBall> pool = new HashMap<>();
int number = 8;
Imperative way:
BowlingBall ballImperative = null;
if (pool.containsKey(number)) {
ballImperative = pool.get(number);
} else {
ballImperative = new BowlingBall(number);
pool.put(number, ballImperative);
}
Functional way:
BowlingBall ballFunctional = pool.values().stream()
.filter(k -> k.getNumber() == number)
.findAny()
.orElseGet(() -> new BowlingBall(number));
pool.put(number, ballFunctional);