Home >Java >javaTutorial >How to Efficiently Initialize a HashMap in Java?

How to Efficiently Initialize a HashMap in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 20:18:11946browse

How to Efficiently Initialize a HashMap in Java?

How to Initialize a HashMap Directly and Concisely

Many Java developers desire a straightforward way to initialize a HashMap with key-value pairs. Unfortunately, Java's standard library lacks a syntax that directly accommodates this.

Java Versions 9 and Higher

However, for Java 9 and later, there's good news! New factory methods have been introduced to simplify map creation:

  • Map.of: Accepts up to 10 key-value pairs in the form of Map.of("key1", "value1", "key2", "value2", ...)
  • Map.ofEntries: Handles any number of entries using Map.ofEntries(entry("key1", "value1"), entry("key2", "value2"), ...)

Example:

// Using Map.of for up to 10 elements
Map<String, String> test1 = Map.of("a", "b", "c", "d");

// Using Map.ofEntries for any number of elements
Map<String, String> test2 = Map.ofEntries(entry("a", "b"), entry("c", "d"));

Java Versions 8 and Below

For earlier Java versions, you'll need to manually add each element. Here's a slightly more concise option using an anonymous subclass initializer:

Example:

Map<String, String> myMap = new HashMap<>() {{
    put("a", "b");
    put("c", "d");
}};

Note:

  • This approach creates an additional class, potentially affecting memory and performance.
  • It may hold a reference to the creating object, preventing garbage collection.

An alternative involving a function:

Example:

Map<String, String> myMap = createMap();

private static Map<String, String> createMap() {
    Map<String,String> myMap = new HashMap<>();
    myMap.put("a", "b");
    myMap.put("c", "d");
    return myMap;
}

The above is the detailed content of How to Efficiently Initialize a HashMap in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn