Last active
August 29, 2015 14:23
-
-
Save eoconnell/bb1465678216c1adc9ea to your computer and use it in GitHub Desktop.
A pretty, but expensive way to create maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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