1 /* 2 * Copyright (C) 2017 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package dagger.internal; 18 19 import static dagger.internal.DaggerCollections.newLinkedHashMapWithExpectedSize; 20 21 import java.util.Collections; 22 import java.util.Map; 23 24 /** 25 * A fluent builder class that returns a {@link Map}. Used in component implementations where a map 26 * must be created in one fluent statement for inlined request fulfillments. 27 */ 28 public final class MapBuilder<K, V> { 29 private final Map<K, V> contributions; 30 MapBuilder(int size)31 private MapBuilder(int size) { 32 contributions = newLinkedHashMapWithExpectedSize(size); 33 } 34 35 /** 36 * Creates a new {@link MapBuilder} with {@code size} elements. 37 */ newMapBuilder(int size)38 public static <K, V> MapBuilder<K, V> newMapBuilder(int size) { 39 return new MapBuilder<>(size); 40 } 41 put(K key, V value)42 public MapBuilder<K, V> put(K key, V value) { 43 contributions.put(key, value); 44 return this; 45 } 46 putAll(Map<K, V> map)47 public MapBuilder<K, V> putAll(Map<K, V> map) { 48 contributions.putAll(map); 49 return this; 50 } 51 build()52 public Map<K, V> build() { 53 switch (contributions.size()) { 54 case 0: 55 return Collections.emptyMap(); 56 default: 57 return Collections.unmodifiableMap(contributions); 58 } 59 } 60 } 61