Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.