Optional in Java 8

Optional in Java 8

In the Java programming language, Optional is a user-defined class data type structure. The Optional class was introduced in the java.util package library in Java 8. The Optional class is primarily used to display a user-defined custom value that may or may not be present in an Optional class.

Optional in Java 8

The Optional class in Java helps mitigate problems or issues arising from null, especially NullPointerException.

import java.util.Optional;

Creating an Optional class in a Java program.

Optional.of() function in the Optional Java class.

The Optional.of() function method is used in a Java program when the Optional class value is defined to be non-null.

Example of Optional.of() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.of(“Vcanhelpsu”);

System.out.println(comp_name);

}

}

its output.

Optional[Vcanhelpsu]

If Java users pass null to of(), it throws a NullPointerException.

Optional<String> comp_name = Optional.of(null); //

Optional.ofNullable()

This method is used in Java when a value can be null.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

String comp_name = null;

Optional<String> output =

Optional.ofNullable(comp_name);

System.out.println(output);

}

}

its output.

Optional.empty

Optional.empty()

This creates an empty Optional element.

Optional<String> output =

Optional.empty();

Checking whether a value is present in the Optional class.

isPresent() function of the Optional class in a Java program.

Returns true if a user-defined search find data value is present in a Java program.

Example of the isPresent() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.of(“Vcanhelpsu”);

if (comp_name.isPresent()) {

System.out.println(comp_name.get());

}

}

}

its output.

Vcanhelpsu

Getting a value in the Java Optional class.

get() function in the Optional Java class.

The get() function method in a Java program returns any user-defined custom value stored inside the Optional.

Example of get() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.of(“Vcanhelpsu”);

String output = comp_name.get();

System.out.println(output);

}

}

As such, calling the get() function on an empty Optional throws a NoSuchElementException.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.empty();

System.out.println(comp_name.get());

}

}

Because of this, the get() function method should be used with caution.

orElse() function in the Optional Java class.

If the orElse() function method in a Java program is empty, it outputs a default value.

Example of the orElse() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.empty();

String output = comp_name.orElse(“Random”);

System.out.println(output);

}

}

its output.

Random

If it contains a value.

Optional<String> comp_name =

Optional.of(“Vcanhelpsu”);

String output =

comp_name.orElse(“Unknown”);

Its output.

Vcanhelpsu

orElseGet() function in the Optional Java class.

The orElseGet() function in a Java program takes a supplier value, which creates a default value if needed in the current program.

Example of orElseGet() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.empty();

String output = comp_name.orElseGet(() -> “Unknown_value”);

System.out.println(output);

}

}

This is the main difference.

orElse(uservalue)

orElseGet(() -> uservalue)

In this example, the orElse() function evaluates its argument even if the optional already has a value, while the orElseGet() supplier evaluates it only if the optional is empty.

The orElseThrow() function in the Optional Java class.

In a Java program, the orElseThrow() function is used to throw an exception if the value is missing.

Example of the orElseThrow() function.

In Java 8, the function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.empty();

String output = comp_name.orElseThrow(

() -> new IllegalArgumentException(“Company Name not found”)

);

System.out.println(output);

}

}

If the value is present, it returns a normal value.

ifPresent() function in the Optional Java class.

In a Java program, the ifPresent() function method executes an action only if a value is present.

Example of the ifPresent() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.of(“Vcanhelpsu”);

comp_name.ifPresent(

n -> System.out.println(“comp_name = ” + n)

);

}

}

its output.

comp_name = Vcanhelpsu

If the optional here is empty, nothing happens.

filter() function in the Optional Java class.

In a Java program, the filter() function returns a value only if it satisfies a condition.

Example of the filter() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<Integer> integers = Optional.of(47);

Optional<Integer> output =

integers.filter(integer -> integer > 31);

System.out.println(output);

}

}

its output.

Optional[47]

if the user-defined condition is false.

Optional<Integer> integers = Optional.of(7);

Optional<Integer> output =

integers.filter(integer -> integer > 31);

System.out.println(output);

its output.

Optional.empty

map() function in the Optional Java class.

The map() function method in a Java program replaces the value inside an Optional.

Example of the map() function.

import java.util.Optional;

public class Main {

public static void main(String[] args) {

Optional<String> comp_name = Optional.of(“Vcanhelpsu”);

Optional<Integer> length =

comp_name.map(String::length);

System.out.println(length);

}

}

its output.

Optional[10]

Its flow is something like this.

“vcanhelpsu”

↓

map(String::length)

↓

10

A complete example of Java Optional.

Instead of writing it this way.

public class Main {

public static void main(String[] args) {

String comp_name = getcomp_name();

if (comp_name != null) {

System.out.println(comp_name.toUpperCase());

} else {

System.out.println(“company name is not available”);

}

public static String getcomp_name() {

return “Vcanhelpsu”;

}

}

Java users can use an Optional.

Optional<String> comp_name =

Optional.ofNullable(getcomp_name());

String output =

comp_name.map(String::toUpperCase)

.orElse(“company name is not available”);

System.out.println(output);

This expression clears the handling of a missing value in the current Java program.

Important java Optional class Methods or function

#Optional MethodPurpose of optional method function
1.of() methodof() method function used tocreates optional with a non-null program value
2.ofNullable() methodofNullable() method function used tocreate optional that may contain null info
3.empty() methodempty() method function used tocreate an empty optional value info
4.isPresent() methodisPresent() method function used tocheck whether value exists or not
5.get() methodget()method function used togets the value define by user
6.ifPresent() methodifPresent() method function performs action if value exists
7.orElse() methodorElse() method function provides a default value
8.orElseGet() methodorElseGet() method function lazily provides a default value
9.orElseThrow() methodorElseThrow() method function used to throw an exception if empty
10.filter() methodfilter() method function used tofilters the optional values
11.map() methodmap() method function used totransforms the optional value

Essential Java Optional Methods.

Simple Flow

                Optional

                      │

┌───────┴───────┐

                    │ │

              Empty Present

                   │ │

get()/map() orElse()

ifPresent() orElseGet()

orElseThrow()

Conclusion of Optional in Java 8.

In the Java programming language, an Optional is a storage container that can hold a user-defined value, or the Optional itself can be empty. The Optional class is primarily useful for specifying the absence of a value and mitigating unsafe null handling exceptions.

Leave a Reply