com.mycila.hc.util.MultiMap.groovy Maven / Gradle / Ivy
/**
* Copyright (C) 2013 Mycila ([email protected])
*
* 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.
*/
package com.mycila.hc.util
/**
* @author Mathieu Carbou ([email protected])
* @date 2014-02-16
*/
class MultiMap implements Iterable>> {
protected final Map> map = [:]
@Override
Iterator>> iterator() {
map.entrySet().iterator()
}
String getString(K key, String join) {
get(key).join(join)
}
Iterator> stringIterator(String join) {
Iterator>> iter = iterator()
return new Iterator>() {
@Override
boolean hasNext() {
return iter.hasNext()
}
@Override
Map.Entry next() {
Map.Entry> e = iter.next()
return new MapEntry(e.key, e.value.join(join))
}
@Override
void remove() {
iter.remove()
}
}
}
boolean isEmpty() {
map.isEmpty()
}
int size() {
map.size()
}
boolean contains(K key) {
map[key] != null
}
void remove(K key) {
map.remove(key)
}
void add(K key, V value) {
if (value == null) {
remove(key)
} else {
if (!contains(key)) {
map[key] = []
}
map[key] << value
}
}
void add(K key, Collection values) {
if (!contains(key)) {
map[key] = []
}
map[key].addAll(values)
}
void addAll(Map map) {
map.each { k, v -> add(k, v) }
}
void put(K key, V value) {
remove(key)
add(key, value)
}
void putAll(Map map) {
map.each { k, v -> put(k, v) }
}
V getFirst(K key) {
List l = get(key)
return l == null || l.size() == 0 ? null : l.get(0)
}
List get(K key) {
map[key] ?: []
}
// groovy support of: map[key]
List getAt(K key) {
return get(key)
}
@Override
String toString() { map }
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy