I am always tired of the very verbose syntax in Java for creating small maps. Arrays.asList(T... a) is very convenient, and therefore I want something similar for a map.
public class MapUtils {
public static <K, V> MapBuilder<K, V> asMap(K key, V value) {
return new MapBuilder<K, V>().entry(key, value);
}
public static class MapBuilder<K, V> extends HashMap<K, V> {
public MapBuilder<K, V> entry(K key, V value) {
this.put(key, value);
return this;
}
}
}
/* Example of how to use asMap */
public class Example {
public void example() {
Map<String, String> map = MapUtil.asMap("key", "value").entry("key2", "value2");
}
}
/* Example of how the one way to create an inline Map in Java */
public class Before {
public void before() {
Map<String, String> map = new HashMap<String, String>() {{
put("key", value");
put("key2", value2");
}};
}
}
Any inputs on how to improve this implementation of MapUtils? Do you consider the asMap-function a good idea, or am I too lazy to write some extra characters?