Java MCQ: Which of the following is true about the Map.ofEntries() method in Java 9?
Answer:
Explanation:
The Map.ofEntries()
method in Java 9 allows the creation of an immutable map with more than 10 entries. Unlike Map.of()
, which is limited to a fixed number of entries, Map.ofEntries()
is more flexible and suitable for creating maps with a larger number of 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),
Entry.of("Doe", 35)
);
System.out.println(ages);
// This will throw UnsupportedOperationException because the map is immutable
// ages.put("Alice", 40);
}
}
In this example, Map.ofEntries()
creates an immutable map with four 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