map-builder-java
Fluent builder for Map
s in Java.
Easily initialize (as expressions) or modify java.util.Map
instances with a DRY, fluent-style builder pattern. No more repeated variable names, static or instance initializer blocks, or double brace initialization. At least until Java 9's Map.of
, and Map.ofEntries
with Map.entry
.
Use
Build a new map (HashMap
by default):
import me.andrz.builder.map.MapBuilder;
// ...
Map<String, Integer> m = new MapBuilder<String, Integer>()
.put( k1, v1 )
.p( k2, v2 )
.putAll( otherMap )
.pa( otherMap2 )
.put( mapEntry )
.p( mapEntry2 )
.remove( k2 )
// ...
.build();
Or, choose a Map
implementation by passing its class:
Map<String, Integer> m = new MapBuilder<String, Integer>(LinkedHashMap.class)
// ...
.build();
Or, pass an existing map to be modified. This also allows choice of Map
implementation:
Map<String, Integer> m = new MapBuilder<String, Integer>(new LinkedHashMap<String, Integer>())
// ...
.build();
Install
Maven
<dependencies>
<dependency>
<groupId>me.andrz</groupId>
<artifactId>map-builder</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
Gradle
repositories {
mavenCentral()
}
dependencies {
compile 'me.andrz:map-builder:1.0.0'
}
Manual
Download JAR from Maven Central.
References
- Apache Commons Collections MapUtils#putAll
- Guava ImmutableMap.Builder
- http://minborgsjavapot.blogspot.com/2014/12/java-8-initializing-maps-in-smartest-way.html
- https://docs.atlassian.com/jira/6.4.1/com/atlassian/jira/util/collect/MapBuilder.html
- http://stackoverflow.com/a/8879328/851135
- http://stackoverflow.com/a/7345751/851135
- http://stackoverflow.com/a/12228431
- Initialize with list of Objects: https://gist.github.com/shunirr/4577191
- Fluent API for Maps: https://gist.github.com/eeichinger/4442854
- https://code.google.com/p/fluentjava/wiki/GettingStarted#Maps