Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package see613.core.datatypes;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * HashMap of key => list of values
- */
- public class MultiValueMap<K, V> extends HashMap<K, List<V>> {
- private static final long serialVersionUID = 616L;
- private V defaultValue = null;
- public MultiValueMap(Map<? extends K, ? extends List<V>> m) {
- super(m);
- }
- public MultiValueMap(int initialCapacity, float loadFactor) {
- super(initialCapacity, loadFactor);
- }
- public MultiValueMap(int initialCapacity) {
- super(initialCapacity);
- }
- public MultiValueMap() {
- super();
- }
- public List<V> put(K key, V val) {
- return put(key, val, false);
- }
- public List<V> put(K key, V val, boolean withRepeats) {
- List<V> list;
- if ( !containsKey(key) ) {
- list = new ArrayList<V>();
- put(key, list);
- }
- else {
- list = get(key);
- }
- if ( withRepeats || !list.contains(val) ) {
- list.add(val);
- }
- return list;
- }
- public List<V> get(K key) {
- return ( containsKey(key) ) ? super.get(key) : new ArrayList<V>();
- }
- public V getOne(K key, int subIndex) {
- V value = defaultValue;
- if ( containsKey(key) ) {
- List<V> list = get(key);
- if ( list.size() > subIndex ) {
- value = list.get(subIndex);
- }
- }
- return value;
- }
- public V getOne(K key) {
- return getOne(key, 0);
- }
- public int sizeById(K key) {
- return get(key).size();
- }
- public V remove(K key, int subKey) {
- V value = null;
- if ( containsKey(key) ) {
- List<V> list = get(key);
- int subKeyIndex = list.indexOf(subKey);
- if ( subKeyIndex > -1 ) {
- value = list.remove(subKeyIndex);
- }
- if ( list.size() == 0 ) {
- remove(key);
- }
- }
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment