
In Java How to initialize HashMap? How to directly initialize a HashMap (in a literal way).
There are 7 different ways
you can initialize HashMap in Java.
Method-1: Simple Mutable map:
It’s a map which supports modification operations such as add, remove, and clear on it.
Method-2: Collections.singletonMap

Method-3: Collections.singletonMap

Method-4: Java 9 – Map.of()

Method-5: Java 9 – Map.ofEntries()

Method-6: Simple Custom Maps

Method-7: Stream.of – AbstractMap.SimpleEntry

Let’s get started for Java program:
Note: Take a look at comments in Java Program for detailed explanation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
package crunchify.com.java.tutorials; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import static java.util.stream.Collectors.toMap; /** * @author Crunchify.com * Program: In Java how to Initialize HashMap? 7 different ways. */ public class CrunchifyInitiateHashMap { // Method-1 // This is Mutable map: It's a map which supports modification operations such as add, remove, and clear on it. public static Map<String, String> crunchifyMap; static { // Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). crunchifyMap = new HashMap<>(); crunchifyMap.put("company1", "Crunchify"); crunchifyMap.put("company2", "Facebook"); crunchifyMap.put("company3", "Google"); } public static void main(String[] args) { // Method-2 collectionsUnmodifiableMap(); // Method-3 collectionsSingletonMap(); // Method-4 java9Mapof(); // Method-5 java9MapOfEntries(); // Method-6 crunchifySimpleustomMap(); // Method-7 streamOfSimpleEntry(); } // Method-2 private static void collectionsUnmodifiableMap() { System.out.println("\n================== Method-2 ==================\n"); Map<String, String> crunchifyMap = new HashMap<>(); // put(): Associates the specified value with the specified key in this map (optional operation). // If the map previously contained a mapping for the key, the old value is replaced by the specified value. // (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.) crunchifyMap.put("company1", "Crunchify"); crunchifyMap.put("company2", "Facebook"); crunchifyMap.put("company3", "Google"); // getClass(): Returns the runtime class of this Object. // The returned Class object is the object that is locked by static synchronized methods of the represented class. mapIteratorCrunchifyUtils(crunchifyMap); // unmodifiableMap(): Returns an unmodifiable view of the specified map. // Query operations on the returned map "read through" to the specified map, and attempts // to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException. // The returned map will be serializable if the specified map is serializable. Map<String, String> crunchifyUnModifiableMap = new HashMap<>(Collections.unmodifiableMap(crunchifyMap)); mapIteratorCrunchifyUtils(crunchifyUnModifiableMap); crunchifyUnModifiableMap.put("company4", "Crunchify"); mapIteratorCrunchifyUtils(crunchifyUnModifiableMap); } // Simple Map Iterator Utility private static void mapIteratorCrunchifyUtils(Map<String, String> crunchifyMap) { // forEach(): Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. // Unless otherwise specified by the implementing class, actions are performed in the order of entry set iteration (if an iteration order is specified.) // Exceptions thrown by the action are relayed to the caller. crunchifyMap.forEach((key, value) -> crunchifyPrintUtils("\tKey: " + key + ", Value: " + value)); System.out.println("\t\t\t\t======"); } // Simple log utility private static void crunchifyPrintUtils(Object crunchifyObject) { // println(): Prints a String and then terminate the line. // This method behaves as though it invokes print(String) and then println(). System.out.println(crunchifyObject); } // Method-3 private static void collectionsSingletonMap() { System.out.println("\n================== Method-3 =================="); // singletonMap(): Returns an immutable map, mapping only the specified key to the specified value. // The returned map is serializable. Map<String, String> crunchifyMap = new HashMap<>(Collections.singletonMap("company1", "Crunchify")); crunchifyMap.put("company2", "Facebook"); mapIteratorCrunchifyUtils(crunchifyMap); } // Method-4 private static void java9Mapof() { System.out.println("\n================== Method-4 =================="); // Map.of(): Returns an unmodifiable map containing three mappings. See Unmodifiable Maps for details. Map<String, String> crunchifyMap = new HashMap<>(Map.of( "company1", "Crunchify", "company2", "Facebook", "company3", "Google" )); crunchifyMap.put("company4", "Amazon"); mapIteratorCrunchifyUtils(crunchifyMap); } // Method-5 private static void java9MapOfEntries() { System.out.println("\n================== Method-5 =================="); // Map.ofEntries(): Returns an unmodifiable map containing keys and values extracted from the given entries. // The entries themselves are not stored in the map. See Unmodifiable Maps for details. // Since: Java 9 // Throws: NullPointerException – if the key or value is null Map<String, String> crunchifyMap = new HashMap<>(Map.ofEntries( Map.entry("company1", "Crunchify"), Map.entry("company2", "Facebook"), Map.entry("company3", "Google") )); crunchifyMap.put("company4", "Twitter"); mapIteratorCrunchifyUtils(crunchifyMap); } // Method-6 private static void crunchifySimpleustomMap() { System.out.println("\n================== Method-6 =================="); // It works for all Java versions, mutable map. Map<String, String> crunchifyMap = myCrunchifyMap(); crunchifyMap.put("company4", "LinkedIn"); mapIteratorCrunchifyUtils(crunchifyMap); } private static Map<String, String> myCrunchifyMap() { Map<String, String> crunchifyMap = new HashMap<>(); crunchifyMap.put("company1", "Crunchify"); crunchifyMap.put("company2", "Facebook"); crunchifyMap.put("company3", "Google"); return crunchifyMap; } // Method-7 private static void streamOfSimpleEntry() { System.out.println("\n================== Method-7 =================="); // Stream(): A sequence of elements supporting sequential and parallel aggregate operations. // The following example illustrates an aggregate operation using Stream and IntStream. // Stream.of(): Returns a sequential ordered stream whose elements are the specified values. Map<String, String> crunchifyMap = Stream.of( // AbstractMap: Sole constructor. (For invocation by subclass constructors, typically implicit.) // SimpleEntry(): Creates an entry representing a mapping from the specified key to the specified value. new AbstractMap.SimpleEntry<>("company1", "Crunchify"), new AbstractMap.SimpleEntry<>("company2", "Facebook"), new AbstractMap.SimpleEntry<>("company3", "Google")) // collect(): Performs a mutable reduction operation on the elements of this stream using a Collector. // A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), // allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning. .collect( // getKey: Returns the key corresponding to this entry. // getValue: Returns the value corresponding to this entry. toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue) ); crunchifyMap.put("company4", "Microsoft"); mapIteratorCrunchifyUtils(crunchifyMap); } } |
IntelliJ IDEA Result:
Just run above program in IntelliJ IDEA or Eclipse as a Java Application and you should see similar result as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
/Users/app/Library/Java/JavaVirtualMachines/openjdk-17.0.1/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=53352:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/app/Documents/crunchify/github/CrunchifyTutorials/target/classes:/Users/app/Documents/ crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/zxing-2.1.jar: crunchify.com.java.tutorials.CrunchifyInitiateHashMap ================== Method-2 ================== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google ====== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google ====== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google Key: company4, Value: Crunchify ====== ================== Method-3 ================== Key: company1, Value: Crunchify Key: company2, Value: Facebook ====== ================== Method-4 ================== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google Key: company4, Value: Amazon ====== ================== Method-5 ================== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google Key: company4, Value: Twitter ====== ================== Method-6 ================== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google Key: company4, Value: LinkedIn ====== ================== Method-7 ================== Key: company1, Value: Crunchify Key: company2, Value: Facebook Key: company3, Value: Google Key: company4, Value: Microsoft ====== Process finished with exit code 0 |