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.
This commit is contained in:
Ivo 2024-10-04 13:42:43 +02:00 committed by GitHub
parent 6f016c52a2
commit 957fd0cc36
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 16 additions and 0 deletions

View File

@ -483,6 +483,22 @@ public class IterableUtils {
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.
* <p>
* A {@code null} or empty iterator returns an empty {@code Optional}.
* </p>
*
* @param <E> 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 <E> Optional<E> any(final Iterable<E> iterable) {
return Optional.ofNullable(IteratorUtils.find(emptyIteratorIfNull(iterable), x -> true));
}
/**
* Shortcut for {@code get(iterator, 0)}.
* <p>