Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class EZMap<T> {
public static void main(String[] args) {
Map<String,Object> m = hashMap(
bob -> 5,
TheGimp -> 8,
incredibleKoolAid -> "James Taylor",
heyArnold -> new Date()
);
System.out.println(m);
}
private final Map<String,T> map;
private EZMap(Map<String,T> _map, Function<Object,T>[] entries) {
map=_map;
for( Function<Object,T> entry: entries ) {
final Method m;
try {
m = entry.getClass().getDeclaredMethod("apply", Object.class);
} catch (NoSuchMethodException nsme ) { throw new RuntimeException(nsme); }
final Parameter p = m.getParameters()[0];
final String key = p.getName();
final T value = entry.apply(null);
map.put(key,value);
}
}
public static <R> Map<String,R> hashMap(Function<Object, R>... entries) {
return new EZMap<R>(new HashMap<>(), entries).map;
}
public static <R> Map<String,R> treeMap(Function<Object, R>... entries) {
return new EZMap<R>(new TreeMap<>(), entries).map;
}
}
@henrik242
Copy link

henrik242 commented Feb 8, 2017

Not bad! Here's a less evil, more compact, but slightly less pretty attempt: http://stackoverflow.com/a/39510693/13365

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment