All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kolibrifx.common.collections.DefaultHashMap Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2010-2017, KolibriFX AS. Licensed under the Apache License, version 2.0.
 */

package com.kolibrifx.common.collections;

import java.util.HashMap;
import java.util.function.Supplier;

/**
 * Specialized hash map that for missing keys calls a supplier function to set a default value,
 * instead of returning null. The supplier can be a standard {@link Supplier} (which
 * takes no arguments) or a {@link ValueSupplier} which takes the key as an argument.
 * 

* Inspired by python's "collections.defaultdict". */ public class DefaultHashMap extends HashMap { @FunctionalInterface public interface ValueSupplier { V get(K key); } private static final long serialVersionUID = -6024567039608325689L; private final ValueSupplier defaultValueSupplier; public DefaultHashMap(final ValueSupplier defaultValueSupplier) { this.defaultValueSupplier = defaultValueSupplier; } public DefaultHashMap(final Supplier defaultValueSupplier) { this(k -> defaultValueSupplier.get()); } @Override public V get(final Object key) { if (!containsKey(key)) { @SuppressWarnings("unchecked") final K typedKey = (K) key; // bah final V value = defaultValueSupplier.get(typedKey); put(typedKey, value); return value; } return super.get(key); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy