Java Optional

class Test { public static void main(String[] args) { Optional<String> stringOptional = Optional.ofNullable(“value1”); stringOptional.map(value -> value.concat(“234”)) .ifPresent(System.out::println); } } Output: value1234 2. Using the flatMap() method class Student { private String firstName; private String lastName; private int grade; private Optional<String> address; public Student(String firstName, String lastName, int grade) { this.firstName = firstName; this.lastName = lastName;…

Read More Optional – map() and flatMap() operations

public Optional<T> filter(Predicale<T> predicate) class Test { public static void main(String[] args) { Optional<String> stringOptional = Optional.ofNullable(“alegru coding”); stringOptional.filter(str -> str.length() > 10) .map(String::toUpperCase) .ifPresent(System.out::println); } } Output: ALEGRU CODING class Test { public static void main(String[] args) { Optional<User> userOptional = Optional.ofNullable(new User(“John”, “john123”, “premium”, “5th Avenue”)); userOptional.filter(user -> user.getMembershipType().equals(“premium”)) .ifPresent(System.out::println); } } class…

Read More Optional – filter() operation

In this lesson, we will cover the three useful methods from the Optional class: public T orElse(T other) – It returns the value if present, otherwise returns the other. public T orElseGet(Supplier<? extends T> other) – It returns the value if present. Otherwise, invoke other and return the result of that invocation. public <X extends…

Read More Optional – orElse(), orElseGet() and orElseThrow() methods

We have the isPresent() and ifPresent() methods to help us detect if Optional contains some value or not. Optional isPresent() method The isPresent() method returns true if there is a value present in the Optional, otherwise false.Using it, we can avoid getting an exception when trying to get the value from an empty Optional. So…

Read More Optional – ifPresent() and isPresent() methods

class Test { public static void main(String[] args) { Optional optional = Optional.empty(); // creates an empty Optional if (optional.isEmpty()) { System.out.println(“It is an empty Optional.”); } else { System.out.println(“Optional is not empty.”); } } } Output: It is an empty Optional. 2. Optional.of(T value) method class Test { public static void main(String[] args) {…

Read More Introduction to Optional class in Java