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 *      http://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     *
    040     * @param <T>      the type of the argument the consumer accepts.
    041     * @since 3.15.0
    042     */
    043    public static <T> void accept(final Consumer<T> consumer, final T object) {
    044        if (consumer != null) {
    045            consumer.accept(object);
    046        }
    047    }
    048
    049    /**
    050     * Gets the NOP Consumer singleton.
    051     *
    052     * @param <T> type type to consume.
    053     * @return the NOP Consumer singleton.
    054     */
    055    @SuppressWarnings("unchecked")
    056    public static <T> Consumer<T> nop() {
    057        return NOP;
    058    }
    059
    060    private Consumers() {
    061        // No instances.
    062    }
    063}