4 ms·
FYI Guava gives you those constructors, the map is: ImmutableMap.of(Key, Value, Key, Value...); For ones with more than 4 values you will need: ImmutableMap<
by RyanHamilton 11y ago
FYI Guava gives you those constructors, the map is:
ImmutableMap.of(Key, Value, Key, Value...);
For ones with more than 4 values you will need:
ImmutableMap<String, Integer> WORD_TO_INT =
new ImmutableMap.Builder<String, Integer>()
.put("one", 1)
.put("two", 2)
.put("three", 3)
.build();
- twic 11y agoYes, 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.