📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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.
Comments
Post a Comment
Leave Comment