أين لازيماب Google-Collection؟
-
19-09-2019 - |
سؤال
أحد المفضلات من مفضلاتي من مجموعات Apache Commons - كان اللزيماب الذي سيستخدم محولا لقيم إنشاء مثيل عند القيام به map.get(newKey); // Will not return null!
.
لماذا لا تحتوي مجموعات Google نفس الشيء؟
المحلول
منذ 10.0، تحتوي الجوافة على فئة جديدة cachebuilder. بدلا من ذلك، وهو متوافق مع GWT.
نصائح أخرى
تسمى new MapMaker().makeComputingMap(Function<? super K, ? extends V> computer)
مدهش.
لاحظ أن MAP Maker هو مصنع - يمكنك إجراء واحد، تعيين جميع أنواع مرجع الكائنات، خصائص التمدد (وحتى وقت انتهاء صلاحية الكائن!)، ثم قم بإنشاء الكثير من خرائط الحوسبة (أو أنواع أخرى) مع مكالمات سطر واحد.
على سبيل المثال، مثل كل شيء آخر تقريبا حول مكتبة مجموعات Google، فهو جيد حقا - بمجرد اكتشافك "
أقترح أن أكتب الخاصة بك
public class LazyMap<K, V> extends ForwardingMap<K, V> {
final Function<? super K, ? extends V> factory;
final Map<K, V> delegate;
public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Supplier<? extends V> supplier) {
return new LazyMap<>(map, supplier);
}
public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Function<? super K, ? extends V> factory) {
return new LazyMap<>(map, factory);
}
private LazyMap(final Map<K, V> map, final Function<? super K, ? extends V> factory) {
this.factory = factory;
this.delegate = map;
}
private LazyMap(final Map<K, V> map, final Supplier<? extends V> supplier) {
this.factory = Functions.forSupplier(supplier);
this.delegate = map;
}
@Override
protected Map<K, V> delegate() {
return delegate;
}
@Override
public V get(final Object key) {
if (delegate().containsKey(key) == false) {
@SuppressWarnings("unchecked")
final K castKey = (K) key;
final V value = factory.apply(castKey);
delegate().put(castKey, value);
return value;
}
return delegate().get(key);
}
}
لا تنتمي إلى StackOverflow