The equals() method of the java.util.Optional class compares an Optional object with another object to determine whether they are equal. It returns true when both Optional objects contain equal values or both are empty.
- The method returns a boolean value.
- Two Optional objects containing equal values are considered equal.
- Two empty Optional objects are also considered equal.
Examples:
Input: Optional 1 = Optional[456], Optional 2 = Optional[456]
Output: trueInput: Optional 1 = Optional[456], Optional 2 = Optional.empty
Output: false
Syntax
public boolean equals(Object obj)
The method returns true when both objects are equal; otherwise, it returns false.
Ways to Use equals() Method in Optional
The equals() method is used to compare Optional objects based on their contained values. The following examples demonstrate comparison between two Optional objects.
1. Comparing Optional Objects with Equal Values
The following program compares two Optional objects containing the same integer value.
import java.util.*;
public class OptionalDemo {
public static void main(String[] args) {
Optional<Integer> op1 = Optional.of(456);
System.out.println("Optional 1: " + op1);
Optional<Integer> op2 = Optional.of(456);
System.out.println("Optional 2: " + op2);
System.out.println("Comparing Optional 1 and Optional 2: "
+ op1.equals(op2));
}
}
Output
Optional 1: Optional[456] Optional 2: Optional[456] Comparing Optional 1 and Optional 2: true
Explanation: Both Optional objects contain the same value, 456. Therefore, equals() returns true.
2. Comparing a Present Optional with an Empty Optional
The following program compares an Optional containing a value with an empty Optional.
import java.util.*;
public class OptionalDemo {
public static void main(String[] args) {
Optional<Integer> op1 = Optional.of(456);
System.out.println("Optional 1: " + op1);
Optional<Integer> op2 = Optional.empty();
System.out.println("Optional 2: " + op2);
System.out.println("Comparing Optional 1 and Optional 2: "
+ op1.equals(op2));
}
}
Output
Optional 1: Optional[456] Optional 2: Optional.empty Comparing Optional 1 and Optional 2: false
Explanation: The first Optional contains 456, while the second is empty. Since their contents differ, equals() returns false.