Skip to content

Instantly share code, notes, and snippets.

@samshu
Created May 29, 2017 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samshu/b471f5a2925fa9d9b718795d8bbdfe42 to your computer and use it in GitHub Desktop.
Save samshu/b471f5a2925fa9d9b718795d8bbdfe42 to your computer and use it in GitHub Desktop.
A fluent builder for java Maps
import java.util.Map;
/**
* Fluent builder for {@link Map}'s
*
* @param <K> key type
* @param <V> value type
*/
public class MapBuilder<K, V> {
private Map<K, V> map;
@SuppressWarnings("unchecked")
private MapBuilder(@SuppressWarnings("rawtypes") Class<? extends Map> mapClass) throws InstantiationException, IllegalAccessException {
map = mapClass.newInstance();
}
/**
* @param mapClass Any {@link Map} implementation type. e.g., HashMap.class
*/
public static <K, V> MapBuilder<K, V> builder(@SuppressWarnings("rawtypes") Class<? extends Map> mapClass)
throws InstantiationException,
IllegalAccessException {
return new MapBuilder<K, V>(mapClass);
}
public MapBuilder<K, V> put(K key, V value) {
map.put(key, value);
return this;
}
public Map<K, V> build() {
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment