| 1 | package org.jtoolkit.essence.utils.impl; |
| 2 | |
| 3 | import org.jetbrains.annotations.NotNull; |
| 4 | import org.jetbrains.annotations.Nullable; |
| 5 | |
| 6 | import java.util.*; |
| 7 | |
| 8 | /* |
| 9 | Copyright 2006 Peter Lawrey |
| 10 | |
| 11 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 12 | you may not use this file except in compliance with the License. |
| 13 | You may obtain a copy of the License at |
| 14 | |
| 15 | http://www.apache.org/licenses/LICENSE-2.0 |
| 16 | |
| 17 | Unless required by applicable law or agreed to in writing, software |
| 18 | distributed under the License is distributed on an "AS IS" BASIS, |
| 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 20 | See the License for the specific language governing permissions and |
| 21 | limitations under the License. |
| 22 | */ |
| 23 | |
| 24 | /** |
| 25 | * Implements a one key to many values map. The map is also reversible. A key can have many values, but a value has only one key. |
| 26 | * |
| 27 | * @author Peter Lawrey |
| 28 | */ |
| 29 | public class OneToManyMap<K, V> { |
| 30 | private final Map<K, Set<V>> keyToValues = new LinkedHashMap<K, Set<V>>(); |
| 31 | private final Map<V, K> valueToKey = new LinkedHashMap<V, K>(); |
| 32 | |
| 33 | public void clear() { |
| 34 | keyToValues.clear(); |
| 35 | valueToKey.clear(); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @return the key for a value or null. |
| 40 | */ |
| 41 | @Nullable public K getKey(@NotNull V value) { |
| 42 | return valueToKey.get(value); |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * @return values for a given key. |
| 47 | */ |
| 48 | @SuppressWarnings({"SuspiciousMethodCalls"}) @Nullable public Set<V> getValues(@NotNull Object key) { |
| 49 | return keyToValues.get(key); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Add a key, value combination. A key can have many values. |
| 54 | */ |
| 55 | public void put(@NotNull K key, @NotNull V value) { |
| 56 | K prevKey = valueToKey.put(value, key); |
| 57 | if (prevKey != null) { |
| 58 | Collection<V> vs = keyToValues.get(prevKey); |
| 59 | if (vs != null) { |
| 60 | vs.remove(value); |
| 61 | if (vs.isEmpty()) |
| 62 | keyToValues.remove(prevKey); |
| 63 | } |
| 64 | } |
| 65 | Set<V> vs = keyToValues.get(key); |
| 66 | if (vs == null) keyToValues.put(key, vs = new HashSet<V>()); |
| 67 | vs.add(value); |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Remove all values for a key. |
| 72 | */ |
| 73 | // @Nullable public V remove(@NotNull Object key) { |
| 74 | // return removeKey((K) key); |
| 75 | // } |
| 76 | public void removeKey(@NotNull K key) { |
| 77 | Collection<V> vs = keyToValues.remove(key); |
| 78 | if (vs != null) |
| 79 | for (V v : vs) |
| 80 | valueToKey.remove(v); |
| 81 | } |
| 82 | } |