I'm always excited to take on new projects and collaborate with innovative minds.

Phone

+1 234 567 890

Email

contact@botble.com

Website

https://botble.com

Address

123 Main Street, New York, NY 10001

Social

Java 8 Features - Stream API

Key Features of Optional in Java:
Avoiding Null Checks: Optional helps avoid explicit null checks. Instead of checking if (object == null), you can use Optional to wrap a potentially null value, making it easier to handle the absence of a value without needing to explicitly check for null.

Key Features of Optional in Java:

  1. Avoiding Null Checks: Optional helps avoid explicit null checks. Instead of checking if (object == null), you can use Optional to wrap a potentially null value, making it easier to handle the absence of a value without needing to explicitly check for null.

Optional<String> name = Optional.ofNullable(someValue);
name.ifPresent(value -> System.out.println(value));  // Will only print if value is non-null
 

Fluent API: Optional provides a fluent API with methods like:

  • map(): Transforms the value inside Optional if present.
  • flatMap(): Similar to map(), but the result is another Optional.
  • filter(): Filters the value inside Optional based on a predicate.
  • ifPresent(): Executes a block of code if the value is present.
  • orElse(), orElseGet(): Returns a default value if no value is present.

Example using map():

 

Optional<String> name = Optional.ofNullable("Nitesh");
Optional<String> upperCaseName = name.map(String::toUpperCase);
upperCaseName.ifPresent(System.out::println);  // Outputs "NITESH"
 

 

Preventing NullPointerException: One of the most important benefits of Optional is that it helps prevent NullPointerException. By forcing the developer to handle the potential absence of a value, Optional avoids situations where methods or operations are called on null objects.

Example using orElse() to provide a default value:

 

Optional<String> name = Optional.ofNullable(null);
String result = name.orElse("Default Name");  // Avoids NPE, returns "Default Name"
 

 

Chaining Operations: You can chain multiple operations with Optional, which makes the code more readable and avoids nested null checks.

 

Optional<String> name = Optional.ofNullable("Nitesh");
Optional<String> result = name.filter(s -> s.startsWith("N"))
                             .map(String::toUpperCase);
result.ifPresent(System.out::println);  // Outputs "NITESH"
 

 

Handling Absence: With methods like ifPresentOrElse(), Optional allows handling both the presence and absence of values in a cleaner way.

 

Optional<String> name = Optional.ofNullable("Nitesh");
name.ifPresentOrElse(
   value -> System.out.println("Name is: " + value),
   () -> System.out.println("No name provided")
);
 

 

Key Features: Avoiding Null Checks: With Optional, you don’t need to check if an object is null explicitly. It provides methods to handle the absence of values gracefully. Fluent API: Optional provides various methods like map(), flatMap(), filter(), ifPresent(), and others to deal with the potential absence of values. Preventing NullPointerException: It helps avoid NullPointerException by forcing developers to explicitly handle the absence of values.

 

package com.niteshsynergy.java8;

import com.niteshsynergy.Emp;

import java.util.Optional;

public class OptionalClasses {
   public static void main(String[] args) {
       // Creating employee instances with names
       Emp emp1 = new Emp(1, "Alice", 75000);
       Emp emp2 = new Emp(2, null, 55000);  // emp2 has a null name

       // Example of Optional.ofNullable() to safely wrap potentially null values
       Optional<String> nameOpt1 = Optional.ofNullable(emp1.getName()); // emp1 has a valid name
       Optional<String> nameOpt2 = Optional.ofNullable(emp2.getName()); // emp2 has a null name

       // Using ifPresent() to execute logic if the value is present
       nameOpt1.ifPresent(name -> System.out.println("Name of emp1: " + name)); 
       // Output: Name of emp1: Alice
       nameOpt2.ifPresent(name -> System.out.println("Name of emp2: " + name)); 
       // No output since emp2's name is null

       // Using orElse() to provide a default value when the name is absent (null)
       System.out.println("Name of emp2: " + nameOpt2.orElse("Unknown")); 
       // Output: Unknown (default name is provided since emp2's name is null)

       // Using map() to transform the value if it's present (e.g., converting name to uppercase)
       Optional<String> upperNameOpt1 = nameOpt1.map(name -> name.toUpperCase()); 
       upperNameOpt1.ifPresent(name -> System.out.println("Uppercase Name of emp1: " + name));  
       // Output: Uppercase Name of emp1: ALICE
   }
}


Thank…..

4 min read
नव. 19, 2024
By Nitesh Synergy
Share