diff --git a/src/main/java/org/apache/commons/collections4/IterableUtils.java b/src/main/java/org/apache/commons/collections4/IterableUtils.java index b314474534..accb5b8dab 100644 --- a/src/main/java/org/apache/commons/collections4/IterableUtils.java +++ b/src/main/java/org/apache/commons/collections4/IterableUtils.java @@ -483,6 +483,22 @@ public static E find(final Iterable iterable, final Predicate return IteratorUtils.find(emptyIteratorIfNull(iterable), predicate); } + /** + * Returns an {@link Optional} containing the first element in the + * {@code iterable}, or an empty {@code Optional} if the iterable is + * empty or null. + *

+ * A {@code null} or empty iterator returns an empty {@code Optional}. + *

+ * + * @param the element type + * @param iterable the iterable to search, may be null + * @return an {@code Optional} containing the first element of the iterable or an empty {@code Optional} if the iterable is empty or null + */ + public static Optional any(final Iterable iterable) { + return Optional.ofNullable(IteratorUtils.find(emptyIteratorIfNull(iterable), x -> true)); + } + /** * Shortcut for {@code get(iterator, 0)}. *