This rule raises an issue when a method returns an Optional that wraps a collection, map, or array.

It applies when the type argument of java.util.Optional is an array or a subtype of java.util.Collection or java.util.Map.

Why is this an issue?

Collections, maps, and arrays can represent no result with an empty value. Callers can iterate over or query an empty container without first checking an Optional.

Wrapping these types in Optional creates two ways to represent no result: Optional.empty() and an empty container. This makes the API harder to use and may lead callers to handle equivalent cases differently.

Return the collection, map, or array directly, and return an empty value when no elements, mappings, or values are available.

Optional<List<String>> findNames() { // Noncompliant
  return Optional.empty();
}

Optional<Map<String, String>> findHeaders() { // Noncompliant
  return Optional.empty();
}

Optional<byte[]> readBytes() { // Noncompliant
  return Optional.empty();
}
List<String> findNames() {
  return Collections.emptyList();
}

Map<String, String> findHeaders() {
  return Collections.emptyMap();
}

byte[] readBytes() {
  return new byte[0];
}

Resources

Documentation