Is it possible to have a HashMap return a default value for all keys that are not found in the set?
16 Answers
In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.
8 Comments
getOrDefault is very nice, but requires the default definition every time the map is accessed. Defining a default value once would also have readability benefits when creating a static map of values.private static String get(Map map, String s) { return map.getOrDefault(s, "Error"); }[Update]
As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...).
[Original]
There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public V get(Object k) {
return containsKey(k) ? super.get(k) : defaultValue;
}
}
8 Comments
(v == null) to (v == null && !this.containsKey(k)) in case they purposely added a null value. I know, this is just a corner case, but the author may run into it.!this.containsValue(null). This is subtly different from !this.containsKey(k). The containsValue solution will fail if some other key has been explicitly assigned a value of null. For example: map = new HashMap(); map.put(k1, null); V v = map.get(k2); In this case, v will still be null, correct?Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,
Map<String, String> map = new DefaultedMap<>("[NO ENTRY FOUND]");
String surname = map.get("Surname");
// surname == "[NO ENTRY FOUND]"
You can also pass in an existing map if you're not in charge of creating the map in the first place.
3 Comments
Java 8 introduced a nice computeIfAbsent default method to Map interface which stores lazy-computed value and so doesn't break map contract:
Map<Key, Graph> map = new HashMap<>();
map.computeIfAbsent(aKey, key -> createExpensiveGraph(key));
Origin: http://blog.javabien.net/2014/02/20/loadingcache-in-java-8-without-guava/
Disclamer: This answer doesn't match exactly what OP asked but may be handy in some cases matching question's title when keys number is limited and caching of different values would be profitable. It shouldn't be used in opposite case with plenty of keys and same default value as this would needlessly waste memory.
3 Comments
Can't you just create a static method that does exactly this?
private static <K, V> V getOrDefault(Map<K,V> map, K key, V defaultValue) {
return map.containsKey(key) ? map.get(key) : defaultValue;
}
1 Comment
You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
public V getDefault(K key, V defaultValue) {
if (containsKey(key)) {
return get(key);
}
return defaultValue;
}
}
I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).
3 Comments
get method. On the other hand - your solution doesn't allow using the class via interface, which might often be the case.getDefault method wouldn't be available though the Map interface, so it would only work like a regular HashMap.It does this by default. It returns null.
3 Comments
HashMap just for this functionality when null is perfectly fine.NullObject pattern, though, or don't want to scatter null-checks throughout your code--a desire I completely understand.I found the LazyMap quite helpful.
When the get(Object) method is called with a key that does not exist in the map, the factory is used to create the object. The created object will be added to the map using the requested key.
This allows you to do something like this:
Map<String, AtomicInteger> map = LazyMap.lazyMap(new HashMap<>(), ()->new AtomicInteger(0));
map.get(notExistingKey).incrementAndGet();
The call to get creates a default value for the given key. You specify how to create the default value with the factory argument to LazyMap.lazyMap(map, factory). In the example above, the map is initialized to a new AtomicInteger with value 0.
1 Comment
Not directly, but you can extend the class to modify its get method. Here is a ready to use example: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm
Comments
/**
* Extension of TreeMap to provide default value getter/creator.
*
* NOTE: This class performs no null key or value checking.
*
* @author N David Brown
*
* @param <K> Key type
* @param <V> Value type
*/
public abstract class Hash<K, V> extends TreeMap<K, V> {
private static final long serialVersionUID = 1905150272531272505L;
/**
* Same as {@link #get(Object)} but first stores result of
* {@link #create(Object)} under given key if key doesn't exist.
*
* @param k
* @return
*/
public V getOrCreate(final K k) {
V v = get(k);
if (v == null) {
v = create(k);
put(k, v);
}
return v;
}
/**
* Same as {@link #get(Object)} but returns specified default value
* if key doesn't exist. Note that default value isn't automatically
* stored under the given key.
*
* @param k
* @param _default
* @return
*/
public V getDefault(final K k, final V _default) {
V v = get(k);
return v == null ? _default : v;
}
/**
* Creates a default value for the specified key.
*
* @param k
* @return
*/
abstract protected V create(final K k);
}
Example Usage:
protected class HashList extends Hash<String, ArrayList<String>> {
private static final long serialVersionUID = 6658900478219817746L;
@Override
public ArrayList<Short> create(Short key) {
return new ArrayList<Short>();
}
}
final HashList haystack = new HashList();
final String needle = "hide and";
haystack.getOrCreate(needle).add("seek")
System.out.println(haystack.get(needle).get(0));
Comments
I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:
public static String getString( final JSONObject response,
final String key )
{ return getString( response, key, "" ); }
public static String getString( final JSONObject response,
final String key, final String defVal )
{ return response.containsKey( key ) ? (String)response.get( key ) : defVal; }
public static long getLong( final JSONObject response,
final String key )
{ return getLong( response, key, 0 ); }
public static long getLong( final JSONObject response,
final String key, final long defVal )
{ return response.containsKey( key ) ? (long)response.get( key ) : defVal; }
public static float getFloat( final JSONObject response,
final String key )
{ return getFloat( response, key, 0.0f ); }
public static float getFloat( final JSONObject response,
final String key, final float defVal )
{ return response.containsKey( key ) ? (float)response.get( key ) : defVal; }
public static List<JSONObject> getList( final JSONObject response,
final String key )
{ return getList( response, key, new ArrayList<JSONObject>() ); }
public static List<JSONObject> getList( final JSONObject response,
final String key, final List<JSONObject> defVal ) {
try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; }
catch( ClassCastException e ) { return defVal; }
}
3 Comments
public final Map<String, List<String>> stringMap = new ConcurrentHashMap<String, List<String>>() {
@Nullable
@Override
public List<String> get(@NonNull Object key) {
return computeIfAbsent((String) key, s -> new ArrayList<String>());
}
};
HashMap cause dead loop, so use ConcurrentHashMap instead of HashMap,
Comments
In Map Using getOrDefault method if key is not found we can place the default value in right side parameter.
Converting List to Map by doing grouping Status.
Map<String, Long> mapClaimDecisionSummaryCount = reportList.stream().collect(Collectors.groupingBy(Report::getStatus, Collectors.counting()));
Long status_approved = mapClaimDecisionSummaryCount.getOrDefault("APPROVED", 0L);
Long status_declined = mapClaimDecisionSummaryCount.getOrDefault("DECLINED", 0L);
Long status_cancelled = mapClaimDecisionSummaryCount.getOrDefault("CANCELLED", 0L);//If Key not found it takes defaultValue as 0
Long status_inprogress = mapClaimDecisionSummaryCount.getOrDefault("INPROGRESS", 0L);
System.out.println("APPROVED: "+ status_approved);
System.out.println("DECLINED: "+ status_declined);
System.out.println("CANCELLED: "+ status_cancelled);
System.out.println("INPROGRESS: "+ status_inprogress);
OutPut:
APPROVED: 20
DECLINED: 10
CANCELLED: 5
INPROGRESS: 0
As you see in the above output Status INPROGRESS is not found, so it takes Default value as 0
1 Comment
In mixed Java/Kotlin projects also consider Kotlin's Map.withDefault.
getOrDefault()link