1 package com.github.davidmoten.guavamini;
2
3 import java.util.Collections;
4 import java.util.HashMap;
5 import java.util.LinkedHashMap;
6 import java.util.Map;
7 import java.util.TreeMap;
8 import java.util.function.Function;
9
10 public final class Maps {
11
12 private Maps() {
13
14 }
15
16 private static final int DEFAULT_INITIAL_SIZE = 16;
17 private static final Function<Integer, Map<Object, Object>> FACTORY_HASHMAP =
18 size -> new HashMap<Object, Object>(size);
19 private static final Function<Integer, Map<Object, Object>> FACTORY_TREEMAP =
20 size -> new TreeMap<Object, Object>();
21 private static final Function<Integer, Map<Object, Object>> FACTORY_LINKEDHASHMAP =
22 size -> new LinkedHashMap<Object, Object>(size);
23
24 public static <K, V> Map<K, V> empty() {
25 return Collections.emptyMap();
26 }
27
28 public static <K, V> MapBuilder<K, V> put(K key, V value) {
29 return hashMap().put(key, value);
30 }
31
32 public static Builder treeMap() {
33 return new Builder(FACTORY_TREEMAP);
34 }
35
36 public static Builder hashMap() {
37 return new Builder(FACTORY_HASHMAP);
38 }
39
40 public static Builder linkedHashMap() {
41 return new Builder(FACTORY_LINKEDHASHMAP);
42 }
43
44 public static Builder factory(
45 Function<? super Integer, ? extends Map<Object, Object>> factory) {
46 Preconditions.checkNotNull(factory, "factory cannot be null");
47 return new Builder(factory);
48 }
49
50 public static final class Builder {
51
52 private final Function<? super Integer, ? extends Map<Object, Object>> factory;
53 private int initialSize = DEFAULT_INITIAL_SIZE;
54
55 Builder(Function<? super Integer, ? extends Map<Object, Object>> factory) {
56 this.factory = factory;
57 }
58
59 public Builder initialSize(int initialSize) {
60 Preconditions.checkArgument(initialSize > 0, "initialSize must be greater than 0");
61 this.initialSize = initialSize;
62 return this;
63 }
64
65 @SuppressWarnings("unchecked")
66 public <K, V> MapBuilder<K, V> put(K key, V value) {
67 return new MapBuilder<K, V>((Map<K, V>) factory.apply(initialSize)).put(key, value);
68 }
69 }
70
71 public static final class MapBuilder<K, V> {
72 private final Map<K, V> map;
73
74 MapBuilder(Map<K, V> map) {
75 this.map = map;
76 }
77
78 public MapBuilder<K, V> put(K key, V value) {
79 map.put(key, value);
80 return this;
81 }
82
83 public Map<K, V> build() {
84 return map;
85 }
86
87 public Map<K, V> buildImmutable() {
88 return Collections.unmodifiableMap(map);
89 }
90 }
91
92 }