| 1 | /* |
| 2 | * Copyright (C) 2013. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License version 3 or |
| 6 | * version 2 as published by the Free Software Foundation. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, but |
| 9 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 | * General Public License for more details. |
| 12 | */ |
| 13 | |
| 14 | package uk.me.parabola.util; |
| 15 | |
| 16 | import java.util.Collections; |
| 17 | import java.util.HashMap; |
| 18 | import java.util.LinkedList; |
| 19 | import java.util.List; |
| 20 | |
| 21 | |
| 22 | public class MultiHashMap<K,V> extends HashMap<K,List<V>> { |
| 23 | |
| 24 | /** |
| 25 | * Returns the list of values associated with the given key. |
| 26 | * |
| 27 | * @param key the key to get the values for. |
| 28 | * @return a list of values for the given keys or the empty list of no such |
| 29 | * value exist. |
| 30 | */ |
| 31 | @Override |
| 32 | public List<V> get(Object key) { |
| 33 | List<V> result = super.get(key); |
| 34 | return result == null ? Collections.emptyList() : result; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Add mapping for the given key and value. |
| 39 | * If the key already exists, the value is added to the end of the existing list. |
| 40 | * |
| 41 | * @param key the key |
| 42 | * @param value the value |
| 43 | * @return the value |
| 44 | */ |
| 45 | public V add(K key, V value ) { |
| 46 | super.computeIfAbsent(key, k -> new LinkedList<>()).add(value); |
| 47 | return value; |
| 48 | } |
| 49 | |
| 50 | public V removeMapping(K key, V value) { |
| 51 | List<V> values = super.get(key); |
| 52 | if (values == null) |
| 53 | return null; |
| 54 | |
| 55 | values.remove(value); |
| 56 | |
| 57 | if (values.isEmpty()) |
| 58 | super.remove(key); |
| 59 | |
| 60 | return value; |
| 61 | } |
| 62 | } |
| 63 |