richdougherty commented on code in PR #1435:
URL: https://github.com/apache/commons-lang/pull/1435#discussion_r2296622107
##########
src/main/java/org/apache/commons/lang3/ObjectUtils.java:
##########
@@ -215,6 +216,199 @@ public static boolean anyNull(final Object... values) {
return !allNotNull(values);
}
+ /**
+ * Applies a function to a value if it's not {@code null}. The
+ * function is only applied if the value is not {@code null},
+ * otherwise the method returns {@code null} immediately. If the
+ * value is not {@code null} then the result of the function is
+ * returned.
+ *
+ * <pre>
+ * ObjectUtils.applyIfNotNull("a", String::toUpperCase) = "A"
+ * ObjectUtils.applyIfNotNull(null, String::toUpperCase) = null
+ * ObjectUtils.applyIfNotNull("a", s -> null) = null
+ * </pre>
+ *
+ * Useful when working with expressions that may return {@code null}
+ * as it allows a single-line expression without making temporary
+ * local variables or evaluating expressions twice. Provides an
+ * alternative to using {@link Optional} that is shorter and has
+ * less allocation.
+ *
+ * <pre>
+ * String name = applyIfNotNull(peopleMap.get(key), Person::getName);
+ *
+ * // Alternative - requires local to avoid calling Map.get twice
+ * Person person = peopleMap.get(key);
+ * String name = (person != null) ? person.getName() : null;
+ *
+ * // Alternative with Optional - idiomatic, but longer and requires
+ * // allocation
+ * String name = Optional.ofNullable(peopleMap.get(key))
+ * .map(Person::getName)
+ * .orElse(null);
+ * </pre>
+ *
+ * @param <T> The type of the input value.
+ * @param <R> The type of the returned value.
+ * @param value The value to apply the function to, may be
+ * {@code null}.
+ * @param mapper The function to apply, must not be {@code null}.
+ * @return The result of the function (which may be {@code null})
+ * or {@code null} if the input value is {@code null}.
+ * @since 3.19.0
+ */
+ public static <T, R> R applyIfNotNull(
+ final T value,
Review Comment:
I didn't add `@Nullable` for these methods because they're not in other
methods in this class, but let me know if you want them. It might need some
changes in the project build dependencies though?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]