Create Immutable Map
static <K,V> Map<K,V> of()
static <K,V> Map<K,V> of(K k1, V v1)
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2)
...
...
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
Create Immutable Map Before Java 9 Example
public class ImmutableMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map < String, Integer > numberMapping = new HashMap < > ();
// Adding key-value pairs to a HashMap
numberMapping.put("One", 1);
numberMapping.put("Two", 2);
numberMapping.put("Three", 3);
Collections.unmodifiableMap(numberMapping);
System.out.println(fruits);
}
}
{One=1, Two=2, Three=3}
Create Immutable Map Example - Java 9 Map.ofEntries() Method
package net.javaguides.corejava.java9;
import java.util.Map;
public class ImmutableMapExample {
public static void main(String[] args) {
Map < String, String > fruits = Map.ofEntries(
Map.entry("1", "Banana"),
Map.entry("2", "Apple"),
Map.entry("3", "Mango"),
Map.entry("4", "Orange"));
System.out.println(fruits);
}
}
{1=Banana, 2=Apple, 3=Mango, 4=Orange}
Related Java 9 Posts
- Java 9 Private Methods in Interface with Examples - Learn how to use private methods in interface with examples.
- Java 9 List.of() Method - Create Immutable List Example - In this post, I show you how to create an immutable list using Java 9 provided List.of() static factory method.
- Java 9 Set.of() Method - Create Immutable Set Example - In this post, I show you how to create an immutable Set using Java 9 provided Set.of() static factory method.
- Java 9 Map.ofEntries() Method - Create Immutable Map Example - In this post, I show you how to create an immutable Map using Java 9 provided Map.ofEntries() static factory method.
- Java 9 - Stream API Improvements with Examples - In this article, we will learn what are the Stream API improvements made in Java 9 with an example.
- Java 9 - Optional Class Improvements with Examples - Learn Optional class improvements with examples.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment