/testability-explorer/src/main/java/com/google/test/metric/collection/LazyHashMap.java

http://testability-explorer.googlecode.com/ · Java · 55 lines · 28 code · 8 blank · 19 comment · 2 complexity · 65f33cd8d56053fbcf78921e3f9f962d MD5 · raw file

  1. /*
  2. * Copyright 2009 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * 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, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.google.test.metric.collection;
  17. import java.util.HashMap;
  18. import java.util.Map;
  19. import com.google.common.base.Supplier;
  20. import com.google.common.collect.ForwardingMap;
  21. /**
  22. * Wrap a Map to provide lazy creation of its values.
  23. * @author alexeagle@google.com (Alex Eagle)
  24. */
  25. public class LazyHashMap<K, V> extends ForwardingMap<K,V> {
  26. private final Map<K, V> delegate;
  27. private final Supplier<V> supplier;
  28. public LazyHashMap(Supplier<V> supplier) {
  29. this.delegate = new HashMap<K,V>();
  30. this.supplier = supplier;
  31. }
  32. protected Map<K, V> delegate() {
  33. return delegate;
  34. }
  35. @Override
  36. public V get(Object o) {
  37. V value = delegate.get(o);
  38. if (value == null) {
  39. value = supplier.get();
  40. delegate.put((K)o, value);
  41. }
  42. return value;
  43. }
  44. public static <K,V> Map<K, V> newLazyHashMap(Supplier<V> supplier) {
  45. return new LazyHashMap<K,V>(supplier);
  46. }
  47. }