Map の簡易初期化 #2
「Mapの簡易初期化」の別解。
Nicolas さんが Builder パターンでやっていたりしてそれはそれでいいのだけれども、以下の様なのを思いついた。
package collections; import java.util.HashMap; import java.util.Map; public class MapBuilder { private static class Entry<K, V> implements Map.Entry<K, V> { private K key; private V value; public Entry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } } public static <K, V> Map<K, V> map(Map.Entry<K, V>... entries) { Map<K, V> m = new HashMap<K, V>(); for (Map.Entry<K, V> entry : entries) { m.put(entry.getKey(), entry.getValue()); } return m; } public static <K, V> Map.Entry<K, V> e(K key, V value) { return new Entry(key, value); } }
以下 Usage。
import static collections.MapBuilder.*; Map<String, Integer> numbers = map(e("one", 1), e("two", 2), e("three", 3));
割りと悪くないと思うんだけどどうだろう。