|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.daffodil.lib.util.collections |
| 19 | + |
| 20 | +import scala.collection.mutable |
| 21 | + |
| 22 | +/** |
| 23 | + * TODO: scala 2.12 phase out |
| 24 | + * Compatibility class for 2.12 and 2.13 since MultiMap and inheritance |
| 25 | + * from class mutable.HashMap have been deprecated in 2.13. |
| 26 | + */ |
| 27 | +class MultiMap[K, V] { |
| 28 | + private val underlying = mutable.Map.empty[K, mutable.Set[V]] |
| 29 | + |
| 30 | + def addBinding(key: K, value: V): Unit = |
| 31 | + underlying.getOrElseUpdate(key, mutable.Set.empty) += value |
| 32 | + |
| 33 | + def addBinding(key: K, values: mutable.Set[V]): Unit = { |
| 34 | + values.foreach(addBinding(key, _)) |
| 35 | + } |
| 36 | + |
| 37 | + def removeBinding(key: K, value: V): Unit = |
| 38 | + underlying.get(key).foreach { values => |
| 39 | + values -= value |
| 40 | + if (values.isEmpty) underlying -= key |
| 41 | + } |
| 42 | + |
| 43 | + def get(key: K): Option[mutable.Set[V]] = underlying.get(key) |
| 44 | + |
| 45 | + def keys: Iterable[K] = underlying.keys |
| 46 | + |
| 47 | + def iterator: Iterator[(K, mutable.Set[V])] = underlying.iterator |
| 48 | + |
| 49 | + def filter(func: (K, mutable.Set[V]) => Boolean): MultiMap[K, V] = { |
| 50 | + val filtered = new MultiMap[K, V] |
| 51 | + for ((key, values) <- underlying) { |
| 52 | + if (func(key, values)) { |
| 53 | + filtered.addBinding(key, values) |
| 54 | + } |
| 55 | + } |
| 56 | + filtered |
| 57 | + } |
| 58 | + |
| 59 | + def map[T](func: (K, mutable.Set[V]) => T): collection.Seq[T] = { |
| 60 | + val ret = mutable.ListBuffer.empty[T] |
| 61 | + for ((key, values) <- underlying) { |
| 62 | + ret.append(func(key, values)) |
| 63 | + } |
| 64 | + ret |
| 65 | + } |
| 66 | +} |
0 commit comments