From 957fd0cc36881c26b90e98703190ab91652e9563 Mon Sep 17 00:00:00 2001 From: Ivo <37253375+spijkercenter@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:42:43 +0200 Subject: [PATCH] Add IterableUtils.any() method - Introduces a new utility method 'any()' in IterableUtils - Returns an Optional containing the first element of an Iterable - Handles null and empty iterables, returning an empty Optional The method is named 'any()' to reflect its behavior of returning any element from the Iterable (specifically, the first one). This naming is consistent with similar concepts in other programming languages and libraries where 'any' often denotes "give me any element that satisfies a condition" - in this case, the condition is simply existence within the Iterable. This addition provides a convenient way to safely retrieve the first element of an Iterable, wrapped in an Optional, with null-safety built-in. --- .../commons/collections4/IterableUtils.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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)}. *