org.rajivprab.cava.Mapc Maven / Gradle / Ivy
package org.rajivprab.cava;
import com.google.common.cache.Cache;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* Map related utility functions.
*
* The newHashMap functionality, with Object varargs, has been removed due to numerous type-safety issues uncovered.
* To construct hash-maps with size greater than 5, recommend not using any such initializer below.
*
* Created by rprabhakar on 12/15/15.
*/
public class Mapc {
// Calls cache.get with exception handling that throws the cause itself, and not the wrapping ExecutionException
public static V cacheGet(Cache cache, K key, Callable callable) {
try {
return cache.get(key, callable);
} catch (ExecutionException | UncheckedExecutionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else {
throw new CheckedExceptionWrapper(e.getCause());
}
}
}
public static HashMap newHashMap(K key1, V value1) {
HashMap map = Maps.newHashMap();
map.put(key1, value1);
return map;
}
public static HashMap newHashMap(K key1, V value1,
K key2, V value2) {
HashMap map = newHashMap(key1, value1);
map.put(key2, value2);
return map;
}
public static HashMap newHashMap(K key1, V value1,
K key2, V value2,
K key3, V value3) {
HashMap map = newHashMap(key1, value1, key2, value2);
map.put(key3, value3);
return map;
}
public static HashMap newHashMap(K key1, V value1,
K key2, V value2,
K key3, V value3,
K key4, V value4) {
HashMap map = newHashMap(key1, value1, key2, value2, key3, value3);
map.put(key4, value4);
return map;
}
public static HashMap newHashMap(K key1, V value1,
K key2, V value2,
K key3, V value3,
K key4, V value4,
K key5, V value5) {
HashMap map = newHashMap(key1, value1, key2, value2, key3, value3, key4, value4);
map.put(key5, value5);
return map;
}
}