Java MCQ: Which Java 9 method is used to create an immutable map with multiple entries?
Answer:
Explanation:
The Map.ofEntries()
method, introduced in Java 9, is used to create an immutable map with multiple entries. This method is similar to Map.of()
but allows for the creation of maps with a larger number of entries, making it more suitable for cases where you need to create a map with more than 10 key-value pairs.
Here’s an example of using Map.ofEntries()
:
import java.util.Map;
import java.util.Map.Entry;
public class MapOfEntriesExample {
public static void main(String[] args) {
Map<String, Integer> ages = Map.ofEntries(
Entry.of("John", 25),
Entry.of("Jane", 30),
Entry.of("Jack", 22)
);
System.out.println(ages);
// This will throw UnsupportedOperationException because the map is immutable
// ages.put("Doe", 35);
}
}
In this example, Map.ofEntries()
creates an immutable map with three key-value pairs. The map cannot be modified after creation, and any attempt to do so (e.g., using put()
) will result in an UnsupportedOperationException
.
Map.ofEntries()
is particularly useful when you need to create an immutable map with a larger number of entries, providing a concise and efficient way to do so.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html