Java OptionalInt Class

Introduction

The OptionalInt class in Java, part of the java.util package, is a container object which may or may not contain a primitive int value. It is designed to handle optional primitive int values gracefully, avoiding NullPointerException and providing a more functional approach to dealing with optional values.

Table of Contents

  1. What is the OptionalInt Class?
  2. Common Methods
  3. Examples of Using the OptionalInt Class
  4. Conclusion

1. What is the OptionalInt Class?

The OptionalInt class provides a way to handle optional primitive int values in a functional and expressive manner. Instead of using null references, OptionalInt encapsulates the presence or absence of an int value, making the code more readable and explicit in its intent.

2. Common Methods

  • empty(): Returns an empty OptionalInt instance.
  • of(int value): Returns an OptionalInt with the specified value present.
  • isPresent(): Returns true if there is a value present, otherwise false.
  • ifPresent(IntConsumer consumer): If a value is present, performs the given action with the value, otherwise does nothing.
  • getAsInt(): If a value is present, returns the value, otherwise throws NoSuchElementException.
  • orElse(int other): Returns the value if present, otherwise returns other.
  • orElseGet(IntSupplier other): Returns the value if present, otherwise returns the result produced by the supplying function.
  • orElseThrow(): Returns the contained value if present, otherwise throws NoSuchElementException.
  • orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the contained value if present, otherwise throws an exception provided by the exception supplier.

3. Examples of Using the OptionalInt Class

Example 1: Creating an OptionalInt

This example demonstrates how to create an OptionalInt object with a value and an empty OptionalInt.

import java.util.OptionalInt;

public class OptionalIntExample {
    public static void main(String[] args) {
        OptionalInt nonEmptyOptional = OptionalInt.of(42);
        OptionalInt emptyOptional = OptionalInt.empty();

        System.out.println("Non-empty OptionalInt: " + nonEmptyOptional);
        System.out.println("Empty OptionalInt: " + emptyOptional);
    }
}

Output:

Non-empty OptionalInt: OptionalInt[42]
Empty OptionalInt: OptionalInt.empty

Example 2: Using isPresent and ifPresent

This example shows how to check if a value is present in an OptionalInt and perform an action if it is.

import java.util.OptionalInt;

public class OptionalIntCheckExample {
    public static void main(String[] args) {
        OptionalInt optional = OptionalInt.of(42);

        if (optional.isPresent()) {
            System.out.println("Value is present: " + optional.getAsInt());
        }

        optional.ifPresent(value -> System.out.println("Value is present: " + value));
    }
}

Output:

Value is present: 42
Value is present: 42

Example 3: Using orElse and orElseGet

This example demonstrates how to provide a default value if the OptionalInt is empty.

import java.util.OptionalInt;

public class OptionalIntDefaultExample {
    public static void main(String[] args) {
        OptionalInt optional = OptionalInt.empty();

        int result1 = optional.orElse(0);
        int result2 = optional.orElseGet(() -> 42);

        System.out.println("Result using orElse: " + result1);
        System.out.println("Result using orElseGet: " + result2);
    }
}

Output:

Result using orElse: 0
Result using orElseGet: 42

Example 4: Using orElseThrow

This example shows how to throw an exception if the OptionalInt is empty.

import java.util.OptionalInt;

public class OptionalIntExceptionExample {
    public static void main(String[] args) {
        OptionalInt optional = OptionalInt.empty();

        try {
            int result = optional.orElseThrow(() -> new IllegalArgumentException("Value is not present"));
            System.out.println(result);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Exception: Value is not present

Example 5: Using ifPresent with an IntConsumer

This example demonstrates how to use ifPresent with an IntConsumer to process the value if it is present.

import java.util.OptionalInt;

public class OptionalIntConsumerExample {
    public static void main(String[] args) {
        OptionalInt optional = OptionalInt.of(42);

        optional.ifPresent(value -> System.out.println("Processing value: " + value));
    }
}

Output:

Processing value: 42

4. Conclusion

The OptionalInt class in Java provides a powerful and expressive way to handle optional primitive int values. By using OptionalInt, developers can avoid common pitfalls associated with null references and write more robust, readable, and error-free code. The examples provided demonstrate common usage patterns and highlight the capabilities of the OptionalInt class.

Comments