UnmodifiableMapBuilder.java

/*
 * Copyright (C) 2018 Stein Eldar Johnsen
 *
 * 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 net.morimekta.collect;

import java.util.Collection;
import java.util.Map;

import static java.util.Objects.requireNonNull;

/**
 * Base class for making unmodifiable maps.
 *
 * @param <K> The map key type.
 * @param <V> The map value type.
 * @param <M> The map type.
 * @param <B> The map builder type.
 */
public abstract class UnmodifiableMapBuilder<
        K, V,
        M extends UnmodifiableMapBase<K, V>,
        B extends UnmodifiableMapBuilder<K, V, M, B>>
        implements MapBuilder<K, V> {

    @Override
    public abstract B put(K key, V value);

    @Override
    public abstract B putAll(Map<? extends K, ? extends V> map);

    @Override
    public abstract M build();

    /**
     * Put entry into map.
     *
     * @param entry The entry to put.
     * @return The map builder.
     */
    public B put(Map.Entry<K, V> entry) {
        requireNonNull(entry, "null entry");
        return put(requireNonNull(entry.getKey(), "null key"),
                   requireNonNull(entry.getValue(), "null value"));
    }

    /**
     * Put all entries into map.
     *
     * @param entries Entries to put.
     * @return The map builder.
     */
    @SafeVarargs
    @SuppressWarnings("unchecked,varargs")
    public final B putAll(Map.Entry<K, V>... entries) {
        for (Map.Entry<K, V> entry : entries) {
            requireNonNull(entry, "null entry");
            put(requireNonNull(entry.getKey(), "null key"),
                requireNonNull(entry.getValue(), "null value"));
        }
        return (B) this;
    }

    /**
     * Put all entries from collection into map.
     *
     * @param entries Collection of entries.
     * @return The map builder.
     */
    @SuppressWarnings("unchecked")
    public B putAll(Collection<Map.Entry<K, V>> entries) {
        if (entries.isEmpty()) {
            return (B) this;
        }
        for (Map.Entry<K, V> entry : entries) {
            requireNonNull(entry, "null entry");
            put(requireNonNull(entry.getKey(), "null key"),
                requireNonNull(entry.getValue(), "null value"));
        }
        return (B) this;
    }
}