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 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; this.grade = grade; } public…

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

class Test { public static void main(String[] args) { Optional<String> optional = Optional.ofNullable(“value1”); String valueFromOptional = optional .map(value -> value.toUpperCase()) // if the value is not null, return the transformed value .orElse(“default value”); // if the value is null, return the “default value” System.out.println(valueFromOptional); } } Output: VALUE1 class Test { public static void main(String[]…

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

class Test { public static void main(String[] args) { Optional<String> optional = Optional.ofNullable(“someValue”); if (optional.isPresent()) { System.out.println(“The value is: ” + optional.get()); } else { System.out.println(“Optional is empty.”); } } } Output: The value is: someValue class Test { public static void main(String[] args) { Optional<String> optional = Optional.ofNullable(“someValue”); optional.ifPresent(value -> System.out.println(value)); } } Output:…

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. class Test { public static void main(String[] args) { Optional optional = Optional.of(“STRING…

Read More Introduction to Optional class in Java