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:
parent
6f016c52a2
commit
957fd0cc36
|
@ -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>
|
||||
|
|
Loading…
Reference in New Issue