Source code
Description: source: package: org.apache.commons.lang3.function, class: Consumers

    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.lang3.function;
    019
    020import java.util.function.Consumer;
    021import java.util.function.Function;
    022
    023/**
    024 * Provides {@link Consumer} instances.
    025 *
    026 * @since 3.13.0
    027 */
    028public class Consumers {
    029
    030    /** NOP singleton. */
    031    @SuppressWarnings("rawtypes")
    032    private static final Consumer NOP = Function.identity()::apply;
    033
    034    /**
    035     * Applies the given {@link Consumer} action to the object if the consumer is not {@code null}. Otherwise, does nothing.
    036     *
    037     * @param consumer the consumer to consume.
    038     * @param object   the object to be consumed.
    039     * @param <T>      the type of the argument the consumer accepts.
    040     * @since 3.15.0
    041     */
    042    public static <T> void accept(final Consumer<T> consumer, final T object) {
    043        if (consumer != null) {
    044            consumer.accept(object);
    045        }
    046    }
    047
    048    /**
    049     * Gets the NOP Consumer singleton.
    050     *
    051     * @param <T> type type to consume.
    052     * @return the NOP Consumer singleton.
    053     */
    054    @SuppressWarnings("unchecked")
    055    public static <T> Consumer<T> nop() {
    056        return NOP;
    057    }
    058
    059    private Consumers() {
    060        // No instances.
    061    }
    062}