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

org.csc.phynixx.common.utils.GroupingAssociation Maven / Gradle / Ivy

The newest version!
package org.csc.phynixx.common.utils;

/*
 * #%L
 * phynixx-common
 * %%
 * Copyright (C) 2014 Christoph Schmidt-Casdorff
 * %%
 * 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%
 */


import java.util.*;

/**
 * Associations betweeen Instances of X and Y can be grouped. To join a group  you have to give an assoc you want to share the group. You can assign a group Value to a group
 * Created by christoph on 09.02.14.
 */
public class GroupingAssociation {


    private final Map> mapA = new HashMap>();

    private final Map> mapB = new HashMap>();


    public void associate(X x, Y y) {
        assertSet(mapA, x).add(y);
        assertSet(mapB, y).add(x);
    }


    public Set getX(X x) {
        return getEndpoints(x, mapA);
    }

    public Set getY(Y y) {
        return getEndpoints(y, mapB);
    }


    public void removeX(X x) {
        removeDependents(x, mapA, mapB);
        mapA.remove(x);
    }


    public void removeY(Y y) {
        removeDependents(y, mapB, mapA);
        mapB.remove(y);
    }


    public void disassociate(X x, Y y) {
        removeDependent(x, y, mapA);
        removeDependent(y, x, mapB);
    }


    static  Set getEndpoints(K k, Map> map) {
        Set value = map.get(k);
        if (value == null) {
            return Collections.emptySet();
        }
        return Collections.unmodifiableSet(value);
    }


    static  void removeDependents(K key, Map> map, Map> inverseMap) {
        Set value = map.get(key);
        if (value != null && !value.isEmpty()) {
            for (V v : value) {
                Set keys = inverseMap.get(v);
                if (keys != null && !keys.isEmpty()) {
                    keys.remove(key);
                }
            }
        }
    }

    static  void removeDependent(K k, V v, Map> map) {
        Set value = map.get(k);
        if (value != null && !value.isEmpty()) {
            value.remove(v);
        }
    }


    static  Set assertSet(Map> map, K key) {
        Set value = map.get(key);
        if (value == null) {
            value = new HashSet();
            map.put(key, value);
        }
        return value;
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy