たまにマッピング自体を定数で持ちたかったりする。
でもMapはいまいち初期化しづらい。
staticイニシャライザとかでやるのが一般的?
こういうのを作って
public class MapBuilder<K, V> { private Map<K, V> map = new HashMap<K, V>(); public MapBuilder<K, V> put(K key, V value) { map.put(key, value); return this; } public Map<K, V> build() { return map; } }
こんな感じで初期化したら
public static Map<String, String> map = new MapBuilder<String, String>() .put("いち", "富士") .put("に", "鷹") .put("さん", "茄子") .build();
割と使いやすかったりしないだろうか。
ちなみにこれはGoogleCollectionsLibraryのImmutableMap.Builderの使い方を参考にしている。
でも業務だとライブラリって使えるかわからないし、作ってもいいかな。
おまけ
HashMap以外も使いたいならファクトリ風にするのもいい。
public class MapBuilder<K, V> { private Map<K, V> map = null; public static <T, S> MapBuilder<T, S> newHashMap() { return new MapBuilder<T, S>(new HashMap<T, S>()); } public static <T, S> MapBuilder<T, S> newTreeMap() { return new MapBuilder<T, S>(new TreeMap<T, S>()); } public static <T extends Enum<T>, S> MapBuilder<T, S> newEnumMap(Class<T> keyType) { return new MapBuilder<T, S>(new EnumMap<T, S>(keyType)); } private MapBuilder(Map<K, V> map) { this.map = map; } public MapBuilder<K, V> put(K key, V value) { map.put(key, value); return this; } public Map<K, V> build() { return map; } }