Created
May 29, 2017 11:24
-
-
Save samshu/b471f5a2925fa9d9b718795d8bbdfe42 to your computer and use it in GitHub Desktop.
A fluent builder for java Maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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