summaryrefslogtreecommitdiffstats
path: root/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/MapBuilder.java
blob: 3aa2a56d2fb7e64a6be39ed000a8fae20a501e9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package org.onap.sdc.dcae.catalog.commons;

import java.util.Map;
import java.util.HashMap;
import java.util.function.Function;

import org.onap.sdc.dcae.catalog.commons.MapBuilder;

import java.util.function.BiFunction;

public class MapBuilder<K,V> {

	private Map<K,V> map;

	public MapBuilder() {
		this.map = new HashMap<K,V>();
	}

	public boolean isEmpty() {
		return this.map.isEmpty();
	}

	public MapBuilder<K,V> put(K theKey, V theValue) {
		this.map.put(theKey, theValue);
		return this;
	}

	public MapBuilder<K,V> putOpt(K theKey, V theValue) {
		if (theValue != null) { 
			this.map.put(theKey, theValue);
		}
		return this;
	}

	public MapBuilder<K,V> put(final Map.Entry<? extends K, ? extends V> theEntry) {
		this.map.put(theEntry.getKey(), theEntry.getValue());
		return this;
	}
	
	public MapBuilder<K,V> putOpt(final Map.Entry<? extends K, ? extends V> theEntry) {
		if (theEntry != null) {
			this.map.put(theEntry.getKey(), theEntry.getValue());
		}
		return this;
	}
    
	public MapBuilder<K,V> putAll(final Iterable<? extends Map.Entry<? extends K, ? extends V>> theEntries) {
		for (final Map.Entry<? extends K, ? extends V> e : theEntries) {
			this.map.put(e.getKey(), e.getValue());
		}
		return this;
	}
	
	/* If theEntries contains multiple entries with the same key then the key gets a suffix in order to make it unique
     .. */
//	public MapBuilder forceAll(final Iterable<? extends Map.Entry<? extends K, ? extends V>> theEntries,
		public MapBuilder<K,V> forceAll(final Iterable<? extends Map.Entry<K, V>> theEntries,
														 Function<Map.Entry<K, V> , K> rekeyFunction) {
		for (final Map.Entry<? extends K, ? extends V> e : theEntries) {
			K key = e.getKey();
			if (this.map.containsKey(key))
				key = rekeyFunction.apply((Map.Entry<K,V>)e);
			this.map.put(key, e.getValue());
		}
		return this;
	}

	public MapBuilder<K,V> putAll(final Map<? extends K, ? extends V> theMap) {
		this.map.putAll(theMap);
		return this;
	}  

	public Map<K,V> build() {
		return this.map;
	}

	public Map<K,V> buildOpt() {
		return this.map.isEmpty() ? null : this.map;
	}
}