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

How to Initialize a Java HashMap Directly?

Barbara Streisand
Release: 2024-12-13 05:27:16
Original
959 people have browsed it

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"};
Copy after login

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"));
Copy after login

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");
}};
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template