Ask Your Question

Revision history [back]

The most convenient method for verifying the equality of Optionals is to use the equals() method, which is a standard method available in all Java classes including Optional. This method returns true if the two Optionals are equal, meaning they contain the same value (or both are null). Here's an example:

Optional<String> optional1 = Optional.of("Hello");
Optional<String> optional2 = Optional.of("Hello");
Optional<String> optional3 = Optional.empty();

System.out.println(optional1.equals(optional2)); // true
System.out.println(optional1.equals(optional3)); // false

In this example, equals() returns true for optional1 and optional2 because they both contain the same string value ("Hello"), and false for optional1 and optional3 because optional3 is empty.