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

org.codegeny.beans.model.MapModel Maven / Gradle / Ivy

There is a newer version: 0.0.4
Show newest version
/*-
 * #%L
 * codegeny-beans
 * %%
 * Copyright (C) 2016 - 2018 Codegeny
 * %%
 * 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.
 * #L%
 */
package org.codegeny.beans.model;

import java.util.Map;
import java.util.function.Function;

import static java.util.Collections.emptyMap;
import static java.util.Objects.requireNonNull;

/**
 * An implementation of {@link Model} for a map.
 *
 * @param  The type of the map.
 * @param  The type of the key.
 * @param  The type of the value.
 * @author Xavier DURY
 */
public final class MapModel implements Model {

    private final Function> extractor;
    private final Model keyModel;
    private final Model valueModel;

    MapModel(Function> extractor, Model keyModel, Model valueModel) {
        this.extractor = requireNonNull(extractor);
        this.keyModel = requireNonNull(keyModel);
        this.valueModel = requireNonNull(valueModel);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public  R accept(ModelVisitor visitor) {
        return requireNonNull(visitor).visitMap(this);
    }

    /**
     * Visit the key model.
     *
     * @param visitor The visitor.
     * @param      The result type.
     * @return A result of type <R>.
     */
    public  R acceptKey(ModelVisitor visitor) {
        return this.keyModel.accept(visitor);
    }

    /**
     * Visit the value model.
     *
     * @param visitor The visitor.
     * @param      The result type.
     * @return A result of type <R>.
     */
    public  R acceptValue(ModelVisitor visitor) {
        return this.valueModel.accept(visitor);
    }

    /**
     * Transform a map of type <M> to Map<K, V>
     *
     * @param values The values.
     * @return A map of (key, value).
     */
    public Map toMap(M values) {
        return values == null ? emptyMap() : this.extractor.apply(values);
    }

    /**
     * Get the key model.
     *
     * @return The key model.
     */
    public Model getKeyModel() {
        return this.keyModel;
    }

    /**
     * Get the value model.
     *
     * @return The value model.
     */
    public Model getValueModel() {
        return this.valueModel;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy