/** * Removes all pairs that contain the given single value * @param key * @return */ public boolean removePairsContaining(K key) { Set<Pair<K>> pairs = mapKeyToPairContainingIt.remove(key); boolean ret = pairsSet.removeAll(pairs); // search and remove all the pairs that contain this key and are mapped by other keys. Set<K> keysToRemove = new LinkedHashSet<K>(); for (Entry<K, Set<Pair<K>>> entry : mapKeyToPairContainingIt.entrySet()) { Set<Pair<K>> pairs2 = entry.getValue(); Set<Pair<K>> pairsContainingTheKey = new HashSet<Pair<K>>(); for (Pair<K> pair : pairs2) if (pair.contains(key)) pairsContainingTheKey.add(pair); pairs2.removeAll(pairsContainingTheKey); // if the key to this pair is mapped to no other pairs, remove this key too if (pairs2.isEmpty()) keysToRemove.add(entry.getKey()); } for (K keyToRemove : keysToRemove) mapKeyToPairContainingIt.remove(keyToRemove); return ret; }