Home | History | Annotate | Download | only in internal
      1 /*
      2  * Copyright (C) 2014 Google, Inc.
      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 package dagger.internal;
     17 
     18 import java.util.Map;
     19 import java.util.Map.Entry;
     20 import javax.inject.Provider;
     21 
     22 import static dagger.internal.Collections.newLinkedHashMapWithExpectedSize;
     23 import static java.util.Collections.unmodifiableMap;
     24 
     25 /**
     26  * A {@link Factory} implementation used to implement {@link Map} bindings. This factory returns a
     27  * {@code Map<K, V>} when calling {@link #get} (as specified by {@link Factory}).
     28  *
     29  * @author Chenying Hou
     30  * @since 2.0
     31  *
     32  */
     33 public final class MapFactory<K, V> implements Factory<Map<K, V>> {
     34   private final Map<K, Provider<V>> contributingMap;
     35 
     36   private MapFactory(Map<K, Provider<V>> map) {
     37     this.contributingMap = unmodifiableMap(map);
     38   }
     39 
     40   /**
     41    * Returns a new MapFactory.
     42    */
     43   public static <K, V> MapFactory<K, V> create(Provider<Map<K, Provider<V>>> mapProviderFactory) {
     44     Map<K, Provider<V>> map = mapProviderFactory.get();
     45     return new MapFactory<K, V>(map);
     46   }
     47 
     48   /**
     49    * Returns a {@code Map<K, V>} whose iteration order is that of the elements
     50    * given by each of the providers, which are invoked in the order given at creation.
     51    */
     52   @Override
     53   public Map<K, V> get() {
     54     Map<K, V> result = newLinkedHashMapWithExpectedSize(contributingMap.size());
     55     for (Entry<K, Provider<V>> entry: contributingMap.entrySet()) {
     56       result.put(entry.getKey(), entry.getValue().get());
     57     }
     58     return unmodifiableMap(result);
     59   }
     60 }
     61