
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.
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.
/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
Let me know if you face any issue running this program.
The post In Java how to Initialize HashMap? 7 different ways appeared first on Crunchify.
0 Commentaires