Skip to content

Instantly share code, notes, and snippets.

@tebeka
Created February 7, 2011 17:33
Show Gist options
  • Save tebeka/814781 to your computer and use it in GitHub Desktop.
Save tebeka/814781 to your computer and use it in GitHub Desktop.
import java.util.Map;
import java.util.HashMap;
public class Make {
private Make() {};
@SuppressWarnings(value = "unchecked")
public static <K, V> Map<K, V> map(Object... items) {
if ((items.length % 2) != 0) {
throw new IllegalArgumentException(
String.format("Number of items must be even (was %d)", items.length));
}
Map<K, V> map = new HashMap<K, V>();
for (int i = 0; i < items.length; i+=2) {
map.put((K)(items[i]), (V)(items[i + 1]));
}
return map;
}
}
class Example {
public static void main(String args[]) {
Map<String, Integer> m = Make.map("a", 1, "b", 2);
for (String key : m.keySet()) {
System.out.println(String.format("%s: %d", key, m.get(key)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment