Guava provides us with great factory methods for Java types, such as Maps.newHashMap()
.
But are there also builders for java Maps?
HashM
I had a similar requirement a while back. Its nothing to do with Guava but you can do something like this to be able to cleanly construct a Map
using a fluent builder.
Create a base class that extends Map.
public class FluentHashMap extends LinkedHashMap {
private static final long serialVersionUID = 4857340227048063855L;
public FluentHashMap() {}
public FluentHashMap delete(Object key) {
this.remove(key);
return this;
}
}
Then create the fluent builder with methods that suit your needs:
public class ValueMap extends FluentHashMap {
private static final long serialVersionUID = 1L;
public ValueMap() {}
public ValueMap withValue(String key, String val) {
super.put(key, val);
return this;
}
... Add withXYZ to suit...
}
You can then implement it like this:
ValueMap map = new ValueMap()
.withValue("key 1", "value 1")
.withValue("key 2", "value 2")
.withValue("key 3", "value 3")