Skip to content

Instantly share code, notes, and snippets.

@eoconnell
Last active August 29, 2015 14:23
Show Gist options
  • Save eoconnell/bb1465678216c1adc9ea to your computer and use it in GitHub Desktop.
Save eoconnell/bb1465678216c1adc9ea to your computer and use it in GitHub Desktop.
A pretty, but expensive way to create maps
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map;
// A pretty, but expensive way to create maps
public class MapLiteral {
public static <K,V> Map.Entry<K, V> e(K key, V value) {
return new SimpleEntry<K,V>(key, value);
}
@SafeVarargs
public static <K,V> Map<K,V> hashMap(Map.Entry<K,V>... entries) {
Map<K,V> map = new HashMap<K,V>();
for (Map.Entry<K, V> e : entries) {
map.put(e.getKey(), e.getValue());
}
return map;
}
public static void main(String[] args) {
Map<String,Integer> m = hashMap(
e("A", 3),
e("B", 2),
e("C", 1)
);
System.out.println(m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment