package ysl.utils; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; public class NullHelper { /** * Transforms the provided value if it is not null. * * @param value the value to transform * @param transform the transformation to apply * @param the type of the provided value * @param the return type of the transformation * @return the transformed value or null if the provided value was null */ public static R nullSafeGet(T value, Function transform) { if (value == null) { return null; } return transform.apply(value); } /** * Transforms the provided value if it is not null or computes a default value. * * @param value the original value to transform * @param transform the transformation to apply if the provided value is not null * @param supplier the function to compute a default value if the provided one is null * @param the type of the provided value * @param the type of the returned value */ public static R nullSafeGetOr(T value, Function transform, Supplier supplier) { if (value == null) { return supplier.get(); } return transform.apply(value); } /** * Returns the first non-null value from the provided arguments. * * @throws NullPointerException if there is no non-null value to return */ @SafeVarargs public static T or(T t, Supplier... suppliers) { if (t != null) { return t; } for (Supplier supplier : suppliers) { T t1 = supplier.get(); if (t1 != null) { return t1; } } throw new NullPointerException(); } }