patternjavaMinor
asMap-implementation for Java (based on Arrays.asList)
Viewed 0 times
arraysasmapjavaforbasedaslistimplementation
Problem
I am always tired of the very verbose syntax in Java for creating small maps.
Any inputs on how to improve this implementation of
Arrays.asList(T... a) is very convenient, and therefore I want something similar for a map.public class MapUtils {
public static MapBuilder asMap(K key, V value) {
return new MapBuilder().entry(key, value);
}
public static class MapBuilder extends HashMap {
public MapBuilder entry(K key, V value) {
this.put(key, value);
return this;
}
}
}
/* Example of how to use asMap */
public class Example {
public void example() {
Map 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 map = new HashMap() {{
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?Solution
In my opinion
MapBuilder should contain a Map, not extend one. Another possible design would be to use a single call with varargs:public class MapUtil {
public static Map asMap(Map.Entry... entries) {
Map map = new HashMap();
for(Map.Entry entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
public static Map.Entry e(final K k, final V v) {
return new Map.Entry() {
public K getKey() {
return k;
}
public V getValue() {
return v;
}
public V setValue(V value) {
throw new UnsupportedOperationException("Not supported");
}
};
}
}
import static very.useful.MapUtil.*;
...
Map map = asMap(e("x",1),e("y",2),e("z",3));Code Snippets
public class MapUtil {
public static <K,V> Map<K,V> asMap(Map.Entry<K,V>... entries) {
Map<K,V> map = new HashMap<K,V>();
for(Map.Entry<K,V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
public static <K,V> Map.Entry<K,V> e(final K k, final V v) {
return new Map.Entry<K, V>() {
public K getKey() {
return k;
}
public V getValue() {
return v;
}
public V setValue(V value) {
throw new UnsupportedOperationException("Not supported");
}
};
}
}
import static very.useful.MapUtil.*;
...
Map<String, Integer> map = asMap(e("x",1),e("y",2),e("z",3));Context
StackExchange Code Review Q#3245, answer score: 8
Revisions (0)
No revisions yet.