- Java initialize map with values
- Nested Class Summary
- Nested classes/interfaces declared in class java.util.AbstractMap
- Nested classes/interfaces declared in interface java.util.Map
- Constructor Summary
- Initialize Map with Values in Java
- Using Map.of() and Map.ofEntries()
- Using Java Collections
- Initialize Map as an instance variable
- Initialize Map as a static variable
- Using Double Brace Initialization
- Using Stream Collectors.toMap()
- Conclusion
- See Also
Java initialize map with values
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable , except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations ( get and put ), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the «capacity» of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put ). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that using many keys with the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable , this class may use comparison order among keys to help break ties. Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be «wrapped» using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new HashMap(. ));
The iterators returned by all of this class’s «collection view methods» are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
Nested Class Summary
Nested classes/interfaces declared in class java.util.AbstractMap
Nested classes/interfaces declared in interface java.util.Map
Constructor Summary
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
Initialize Map with Values in Java
In this tutorial, we’ll learn different ways to initialize a Map with values in Java.
Using Map.of() and Map.ofEntries()
It is possible to initialize a Map with values in a single expression if you are using Java 9 or higher version using Map.of() and Map.ofEntries() method. This is shortest possible way so far.
Map.of()
Java 9 provides mutiple Map.of() overloaded methods to initialize a Map with upto 10 key-value pairs.
MapString, Integer> emptyMap = Map.of(); MapString, Integer> singletonMap = Map.of("A", 1); MapString, Integer> map = Map.of("A", 1, "B", 2, "C", 3);
Map.ofEntries()
If you have more than 10 key-value pairs to initialize, then you should use Map.ofEntries() method. This method has no limit and you can define any number of key-value pairs.
MapString, Integer> map = Map.ofEntries( Map.entry("A", 1), Map.entry("B", 2), Map.entry("C", 3), Map.entry("D", 4), Map.entry("E", 5), Map.entry("F", 6), Map.entry("G", 7), Map.entry("H", 8), Map.entry("I", 9), Map.entry("J", 10), Map.entry("K", 11), Map.entry("L", 12) ); map.put("M", 13); // Throw UnsupportedOperationException map.remove("A"); // Throw UnsupportedOperationException
Mutable Map
Thing to note that both Map.of() and Map.ofEntries() return an immutable map which means that adding or removing an element in Map result into java.lang.UnsupportedOperationException exception.
You can avoid this by creating a mutable map (by copying the immutable map to new HashMap ) in this way:-
MapString, Integer> mutableEmptyMap = new HashMap<>(Map.of()); MapString, Integer> mutableSingletonMap = new HashMap<>(Map.of("A", 1)); MapString, Integer> mutableMap = new HashMap<>(Map.ofEntries( Map.entry("A", 1), Map.entry("B", 2), Map.entry("C", 3), Map.entry("D", 4), Map.entry("E", 5), Map.entry("F", 6), Map.entry("G", 7), Map.entry("H", 8), Map.entry("I", 9), Map.entry("J", 10), Map.entry("K", 11), Map.entry("L", 12) )); mutableMap.put("M", 13); // It works! mutableMap.remove("A"); // It works!
Using Java Collections
Java Collections class provide methods to initialize emptyMap() , singletonMap() and unmodifiableMap() . Note that all these methods return immutable map
MapString, Integer> emptyMap = Collections.emptyMap(); MapString, Integer> singletonMap = Collections.singletonMap("A", 1); singletonMap.put("B", 2); // Throw UnsupportedOperationException singletonMap.remove("A"); // Throw UnsupportedOperationException MapString, Integer> mutableMap = new HashMap<>(singletonMap); mutableMap.put("B", 2); // It works! MapString, Integer> immutableMap = Collections.unmodifiableMap(mutableMap); immutableMap.put("B", 2); // Throw UnsupportedOperationException
Initialize Map as an instance variable
If you initialize a Map as an instance variable, keep the initialization in a constructor or instance initializer:-
public class MyClass MapString, Integer> instanceMap = new HashMap<>(); instanceMap.put("A", 1); instanceMap.put("B", 2); > >
Initialize Map as a static variable
If you initialize a Map as a static class variable, keep the initialization in a static initializer:-
public class MyClass static MapString, Integer> staticMap = new HashMap<>(); static staticMap.put("A", 1); staticMap.put("B", 2); > >
Using Double Brace Initialization
You can initialize map with values using Double Brace Initialization:-
MapString, Integer> map = new HashMap<>() < put("A", 1); put("B", 2); >>;
In Double brace initialization > , first brace creates a new Anonymous Inner Class, the second brace declares an instance initializer block that is run when the anonymous inner class is instantiated.
This approach is not recommended as it creates an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects. This may cause memory leaks or problems with serialization.
The alternative approach for this is to create a function to initialize a map:-
// It works for all Java versions, mutable map. MapString, Integer> map = createMap(); map.put("C", "3"); // It works! private static MapString, String> createMap() MapString, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); return map; >
Using Stream Collectors.toMap()
We can also use Java 8 Stream API to initialize a Map with values.
When both key and value are of same type (e.g. String):-
MapString, String> mutableMap1 = Stream.of(new String[][] "A", "a">, "B", "b">, "C", "c"> >).collect(Collectors.toMap(p -> p[0], p -> p[1]));
When both key and value are of different type (e.g. String and Integer):-
MapString, Integer> mutableMap2 = Stream.of(new Object[][] "A", 1>, "B", 2>, "C", 3> >).collect(Collectors.toMap(p -> (String) p[0], p -> (Integer) p[1]));
Another approach that can easily accommodate different types for key and value involves creating a stream of map entries.
MapString, Integer> mutableMap3 = Stream.of( new AbstractMap.SimpleEntry<>("A", 1), new AbstractMap.SimpleEntry<>("B", 2), new AbstractMap.SimpleEntry<>("C", 3)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); MapString, Integer> mutableMap4 = Stream.of( new AbstractMap.SimpleImmutableEntry<>("A", 1), new AbstractMap.SimpleImmutableEntry<>("B", 2), new AbstractMap.SimpleImmutableEntry<>("C", 3)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
The only difference between SimpleEntry and SimpleImmutableEntry is that you can set the value of SimpleEntry instance once initialized whereas set value of SimpleImmutableEntry after initialization throw UnsupportedOperationException .
Note that all the maps we have initialized using streams so far are mutable map means we can add or remove elements from them. You can initialize an immutable map using streams in this way:-
MapString, Integer> map5 = Stream.of( new AbstractMap.SimpleEntry<>("A", 1), new AbstractMap.SimpleEntry<>("B", 2), new AbstractMap.SimpleEntry<>("C", 3)) .collect(Collectors.collectingAndThen( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue), Collections::unmodifiableMap ));
Conclusion
Let’s look at the summary of all the ways to initialize a Map with values:-
- Using Map.of() and Map.ofEntries() – Recommended this single line expression if you use Java 9 and above
- Using Java Collections – Works with all Java versions. Useful to define singleton map upto Java 8
- Using Double Brace Initialization — Avoid Double braces initialization. Create a method instead.
- Initialize Map as an instance variable — Recommended to initialize instance variable
- Initialize Map as a static variable — Recommended to initialize static variable
- Using Stream Collectors.toMap() – Too many lines of code. We can use other alternatives if possible to avoid boilerplate code.
See Also
Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.