Video in progress
Why do you need Optional, and what's the right way to use it?
Optional<T> is a container that states "there might be no value" openly in the method signature. It's mainly used as a return type: the caller can't walk past the "no value" case without thinking about it.
📖 Answer
Optional<User> findByPhone(String phone);
String name = users.findByPhone(phone)
.map(User::getName)
.orElse("Mehmon");
User u = users.findByPhone(phone)
.orElseThrow(() -> new NotFoundException("Foydalanuvchi topilmadi"));
Useful methods: map, filter, flatMap, orElse, orElseGet, orElseThrow, ifPresent, ifPresentOrElse.
The difference between orElse and orElseGet:
opt.orElse(loadDefault()); // loadDefault() is always called
opt.orElseGet(() -> loadDefault()); // only if there's no value
Mistakes you see a lot:
opt.get()without a check: the same NPE again, just under a different name;if (opt.isPresent()) { opt.get()... }works, butmap/ifPresentis cleaner;Optionalas a field, a method parameter or a collection element: don't do it;Optional<List<...>>: returning an empty list is enough.
Sign up to mark studied questions and save your progress.