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

uk.gov.gchq.gaffer.mapstore.multimap.MapOfSets Maven / Gradle / Ivy

There is a newer version: 2.3.1
Show newest version
/*
 * Copyright 2017-2020 Crown Copyright
 *
 * 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 uk.gov.gchq.gaffer.mapstore.multimap;

import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MapOfSets implements MultiMap {
    private final Map> multiMap;

    /**
     * The type of Set to use.
     * If null then a {@link HashSet} will be used.
     */
    private final Class setClass;

    public MapOfSets(final Map> multiMap) {
        this(multiMap, null);
    }

    public MapOfSets(final Map> multiMap, final Class setClass) {
        this.multiMap = multiMap;
        this.setClass = setClass;
    }

    @Override
    public boolean put(final K key, final V value) {
        final Set values = multiMap.computeIfAbsent(key, k -> createSet());
        return values.add(value);
    }

    @Override
    public void put(final K key, final Collection value) {
        final Set existingValue = multiMap.get(key);
        if (null == existingValue) {
            if (value instanceof Set) {
                multiMap.put(key, ((Set) value));
            } else {
                multiMap.put(key, Sets.newHashSet(value));
            }
        } else {
            existingValue.addAll(value);
        }
    }

    @Override
    public Collection get(final K key) {
        return multiMap.get(key);
    }

    @Override
    public Set keySet() {
        return multiMap.keySet();
    }

    public Collection>> entrySet() {
        return multiMap.entrySet();
    }

    @Override
    public void clear() {
        multiMap.clear();
    }

    protected Set createSet() {
        final Set values;
        if (null == setClass) {
            values = new HashSet<>();
        } else {
            try {
                values = setClass.newInstance();
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new IllegalArgumentException("Unable to create new instance of set " + setClass.getName(), e);
            }
        }
        return values;
    }

    public Map> getWrappedMap() {
        return multiMap;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy