Builder for HashMap

Guava provides us with excellent factory methods for Java types, such as Maps.newHashMap() .

But are there also constructors for java maps?

 HashMap<String,Integer> m = Maps.BuildHashMap. put("a",1). put("b",2). build(); 
+102
java collections guava
Sep 08 2018-11-11T00:
source share
11 answers

Since the Java 9 Map interface contains:

  • Map.of(k1,v1, k2,v2,..)
  • Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2),..) .

The limitations of these factory methods are that they:

  • cannot contain null as keys and / or values ​​(if you need to keep zeros, look at other answers)
  • produce invariable cards

If we need mutable maps, we can use the copy constructor of the selected mutable map and pass the result of Map.of(..) as

 Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") ); 
+4
May 30 '19 at 18:11
source share

There is no such thing for HashMaps, but you can create an ImmutableMap using the builder:

 final Map<String, Integer> m = ImmutableMap.<String, Integer>builder(). put("a", 1). put("b", 2). build(); 

And if you need a modified map, you can just pass it to the HashMap constructor.

 final Map<String, Integer> m = Maps.newHashMap( ImmutableMap.<String, Integer>builder(). put("a", 1). put("b", 2). build()); 
+155
Sep 08 2018-11-11T00:
source share

Not really a builder, but using an initializer:

 Map<String, String> map = new HashMap<String, String>() {{ put("a", "1"); put("b", "2"); }}; 
+44
Sep 08 2018-11-11T00:
source share

This is similar to the accepted answer, but a little cleaner in my opinion:

 ImmutableMap.of("key1", val1, "key2", val2, "key3", val3); 

There are several variations of the method described above, and they are great for creating static, immutable, immutable maps.

+35
Sep 11 '14 at 19:24
source share

A simple map constructor is trivial to write:

 public class Maps { public static <Q,W> MapWrapper<Q,W> map(Q q, W w) { return new MapWrapper<Q, W>(q, w); } public static final class MapWrapper<Q,W> { private final HashMap<Q,W> map; public MapWrapper(Q q, W w) { map = new HashMap<Q, W>(); map.put(q, w); } public MapWrapper<Q,W> map(Q q, W w) { map.put(q, w); return this; } public Map<Q,W> getMap() { return map; } } public static void main(String[] args) { Map<String, Integer> map = Maps.map("one", 1).map("two", 2).map("three", 3).getMap(); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } } } 
+8
Jul 30 '14 at 9:37
source share

Here is a very simple ...

 public class FluentHashMap<K, V> extends java.util.HashMap<K, V> { public FluentHashMap<K, V> with(K key, V value) { put(key, value); return this; } public static <K, V> FluentHashMap<K, V> map(K key, V value) { return new FluentHashMap<K, V>().with(key, value); } } 

then

 import static FluentHashMap.map; HashMap<String, Integer> m = map("a", 1).with("b", 2); 

See https://gist.github.com/culmat/a3bcc646fa4401641ac6eb01f3719065.

+7
Jun 22 '17 at 9:10
source share

You can use:

 HashMap<String,Integer> m = Maps.newHashMap( ImmutableMap.of("a",1,"b",2) ); 

It's not so cool and readable, but it does the job.

+6
Sep 08 '11 at 8:32
source share

HashMap is mutable; no builder needed.

 Map<String, Integer> map = Maps.newHashMap(); map.put("a", 1); map.put("b", 2); 
+4
Sep 08 '11 at 12:15
source share

I had a similar requirement a while ago. This has nothing to do with Guava, but you can do something similar to be able to build a Map using a free builder.

Create a base class that extends Map.

 public class FluentHashMap<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 4857340227048063855L; public FluentHashMap() {} public FluentHashMap<K, V> delete(Object key) { this.remove(key); return this; } } 

Then create a free builder using methods that suit your needs:

 public class ValueMap extends FluentHashMap<String, Object> { 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... } 

Then you can implement it as follows:

 ValueMap map = new ValueMap() .withValue("key 1", "value 1") .withValue("key 2", "value 2") .withValue("key 3", "value 3") 
0
Apr 13 '17 at 9:59 on
source share

This is what I always wanted, especially when setting up test instruments. Finally, I decided to write a simple free builder that could build any implementation of the Map - https://gist.github.com/samshu/b471f5a2925fa9d9b718795d8bbdfe42#file-mapbuilder-java

  /** * @param mapClass Any {@link Map} implementation type. eg, 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; } 
0
May 29 '17 at 11:32
source share

Here is one I wrote

 import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; public class MapBuilder<K, V> { private final Map<K, V> map; /** * Create a HashMap builder */ public MapBuilder() { map = new HashMap<>(); } /** * Create a HashMap builder * @param initialCapacity */ public MapBuilder(int initialCapacity) { map = new HashMap<>(initialCapacity); } /** * Create a Map builder * @param mapFactory */ public MapBuilder(Supplier<Map<K, V>> mapFactory) { map = mapFactory.get(); } public MapBuilder<K, V> put(K key, V value) { map.put(key, value); return this; } public Map<K, V> build() { return map; } /** * Returns an unmodifiable Map. Strictly speaking, the Map is not immutable because any code with a reference to * the builder could mutate it. * * @return */ public Map<K, V> buildUnmodifiable() { return Collections.unmodifiableMap(map); } } 

You use it like this:

 Map<String, Object> map = new MapBuilder<String, Object>(LinkedHashMap::new) .put("event_type", newEvent.getType()) .put("app_package_name", newEvent.getPackageName()) .put("activity", newEvent.getActivity()) .build(); 
0
Feb 15 '19 at 17:19
source share



All Articles