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

org.jhotdraw8.icollection.facade.ReadOnlyMapFacade Maven / Gradle / Ivy

/*
 * @(#)ReadOnlyMapFacade.java
 * Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
 */

package org.jhotdraw8.icollection.facade;

import org.jhotdraw8.icollection.readonly.ReadOnlyMap;
import org.jspecify.annotations.Nullable;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Provides a {@link ReadOnlyMap} facade to a set of {@code ReadOnlyMap} functions.
 *
 * @param  the key type
 * @param  the value type
 * @author Werner Randelshofer
 */
public class ReadOnlyMapFacade implements ReadOnlyMap {
    protected final Supplier>> iteratorFunction;
    protected final IntSupplier sizeFunction;
    protected final Predicate containsKeyFunction;
    protected final Function getFunction;


    public ReadOnlyMapFacade(ReadOnlyMap m) {
        this(m::iterator, m::size, m::containsKey, m::get);
    }

    public ReadOnlyMapFacade(Map m) {
        this(() -> m.entrySet().iterator(), m::size, m::containsKey, m::get);
    }

    public ReadOnlyMapFacade(Supplier>> iteratorFunction,
                             IntSupplier sizeFunction,
                             Predicate containsKeyFunction,
                             Function getFunction) {
        this.iteratorFunction = iteratorFunction;
        this.sizeFunction = sizeFunction;
        this.containsKeyFunction = containsKeyFunction;
        this.getFunction = getFunction;
    }

    @Override
    public @Nullable V get(Object key) {
        @SuppressWarnings("unchecked") K unchecked = (K) key;
        return getFunction.apply(unchecked);
    }

    @Override
    public boolean containsKey(Object key) {
        return containsKeyFunction.test(key);
    }

    @Override
    public boolean isEmpty() {
        return sizeFunction.getAsInt() == 0;
    }

    @Override
    public Iterator> iterator() {
        return iteratorFunction.get();
    }

    @Override
    public int size() {
        return sizeFunction.getAsInt();
    }

    public boolean containsEntry(final @Nullable Object o) {
        if (o instanceof Map.Entry) {
            @SuppressWarnings("unchecked") Map.Entry entry = (Map.Entry) o;
            K key = entry.getKey();
            return containsKey(key) && Objects.equals(entry.getValue(), get(key));
        }
        return false;
    }

}