Creating PM-producer
[nonrtric/plt/ranpm.git] / pmproducer / src / main / java / org / oran / pmproducer / repository / MultiMap.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019-2021 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oran.pmproducer.repository;
22
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.Vector;
30
31 /**
32  * A map, where each key can be bound to may values (where each value has an own
33  * ID)
34  */
35 public class MultiMap<T> {
36
37     private final Map<String, Map<String, T>> map = new HashMap<>();
38
39     public void put(String key, String id, T value) {
40         this.map.computeIfAbsent(key, k -> new HashMap<>()).put(id, value);
41     }
42
43     public T remove(String key, String id) {
44         Map<String, T> innerMap = this.map.get(key);
45         if (innerMap != null) {
46             T removedElement = innerMap.remove(id);
47             if (innerMap.isEmpty()) {
48                 this.map.remove(key);
49             }
50             return removedElement;
51         }
52         return null;
53     }
54
55     public T get(String key1, String key2) {
56         Map<String, T> innerMap = this.map.get(key1);
57         if (innerMap == null) {
58             return null;
59         }
60         return innerMap.get(key2);
61     }
62
63     public Collection<T> get(String key) {
64         Map<String, T> innerMap = this.map.get(key);
65         if (innerMap == null) {
66             return Collections.emptyList();
67         }
68         return new Vector<>(innerMap.values());
69     }
70
71     public Set<String> keySet() {
72         return this.map.keySet();
73     }
74
75     public Collection<T> values() {
76         ArrayList<T> result = new ArrayList<>();
77         for (String key : keySet()) {
78             result.addAll(get(key));
79         }
80         return result;
81     }
82
83     public void clear() {
84         this.map.clear();
85     }
86
87 }