All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.httprpc.util.Optionals Maven / Gradle / Ivy

There is a newer version: 9.5
Show newest version
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.httprpc.util;

import java.util.function.Function;

/**
 * Class that provides static utility methods for working with optional values.
 */
public class Optionals {
    /**
     * Returns the first non-null value in a sequence of values.
     *
     * @param values
     * The sequence of values.
     *
     * @param 
     * The type of the values in the sequence.
     *
     * @return
     * The first non-null value in the sequence.
     */
    @SafeVarargs
    public static  T coalesce(T... values) {
        for (int i = 0; i < values.length; i++) {
            T value = values[i];

            if (value != null) {
                return value;
            }
        }

        return null;
    }

    /**
     * Maps a non-null value to another value.
     *
     * @param value
     * The value to map.
     *
     * @param mapper
     * The mapping function.
     *
     * @param 
     * The original value type.
     *
     * @param 
     * The mapped value type.
     *
     * @return
     * The mapped value, or null if the original value is
     * null.
     */
    public static  U map(T value, Function mapper) {
        return (value == null) ? null : mapper.apply(value);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy