Home >Java >javaTutorial >How to Initialize a Java HashMap Directly?

How to Initialize a Java HashMap Directly?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 05:27:161022browse

How to Initialize a Java HashMap Directly?

How to initialize a HashMap directly (in a literal way)?

Question:
Is it possible to initialize a Java HashMap in a concise way like this?

Map<String,String> test = 
    new HashMap<String, String>{"test":"test","test":"test"};

If so, what is the correct syntax?

Answer for Java Version 9 or higher:

Yes, this is now possible using factory methods added in Java 9:

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

// For any number of elements
import static java.util.Map.entry;
Map<String, String> test2 = Map.ofEntries(entry("a", "b"), entry("c", "d"));

Answer for up to Java Version 8:

Unfortunately, direct initialization in the provided syntax is not possible. However, you can use an anonymous subclass to shorten the code:

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

Alternatively, you can create a function for initialization:

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

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

The above is the detailed content of How to Initialize a Java HashMap Directly?. 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