3 ms·
Yes, that's the most orthodox Java solution to this. It's not hard to do slightly better (IMHO!), though: public class MapBuilder<K, V> { public static <K
by twic 11y ago
Yes, that's the most orthodox Java solution to this.
It's not hard to do slightly better (IMHO!), though:
public class MapBuilder<K, V> {
public static <K, V> MapBuilder<K, V> with(K key, V value) {
return new MapBuilder<K, V>().and(key, value);
}
private List<Map.Entry<K, V>> entries = new ArrayList<>();
public MapBuilder<K, V> and(K key, V value) {
entries.add(new AbstractMap.SimpleEntry<>(key, value));
return this;
}
public Map<K, V> build(Map<K, V> map) {
for (Map.Entry<K, V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
public Map<K, V> build(Supplier<Map<K, V>> mapSupplier) {
return build(mapSupplier.get());
}
}
Which lets you write:
Map<String, Boolean> map = with("Java", true).and("Go", false).build(new HashMap<String, Boolean>());
Map<String, Boolean> map2 = with("Java", true).and("Go", false).build(Map::new);
I don't have Java 8 on the machine i'm on right now, so apologies if the second example doesn't compile; it might need more manifest types on it.