Creating and Initializing Maps
suggest changeIntroduction
A Map stores key/value pairs: each key has one associated value, and lookup by key is fast. This is also called an associative array. In Java, maps use the Map interface, which does not extend Collection. HashMap does not guarantee print order.
- Way 1 :-
/*J2SE < 5.0*/
Map map = new HashMap();
map.put("name", "A");
map.put("address", "Malviya-Nagar");
map.put("city", "Jaipur");
System.out.println(map);
- Way 2 :-
/*J2SE 5.0+ style (use of generics):*/
Map<String, Object> map = new HashMap<>();
map.put("name", "A");
map.put("address", "Malviya-Nagar");
map.put("city", "Jaipur");
System.out.println(map);
- Way 3 :-
Map<String, Object> map = new HashMap<String, Object>(){{
put("name", "A");
put("address", "Malviya-Nagar");
put("city", "Jaipur");
}};
System.out.println(map);
Double-brace initialization creates an anonymous HashMap subclass. In an instance method, that subclass captures the enclosing instance.
- Way 4 :-
Map<String, Object> map = new TreeMap<String, Object>();
map.put("name", "A");
map.put("address", "Malviya-Nagar");
map.put("city", "Jaipur");
System.out.println(map);
- Way 5 :-
//Java 8
final Map<String, String> map =
Arrays.stream(new String[][] {
{ "name", "A" },
{ "address", "Malviya-Nagar" },
{ "city", "jaipur" },
}).collect(Collectors.toMap(m -> m[0], m -> m[1]));
System.out.println(map);
- Way 6 :-
// Initialize a static map outside any method.
final static Map<String, String> map;
static
{
map = new HashMap<String, String>();
map.put("a", "b");
map.put("c", "d");
}
- Way 7 :- Creating an immutable single key-value map.
// Immutable single key-value map
Map<String, String> singletonMap = Collections.singletonMap("key", "value");
The map cannot be modified. Any attempt throws UnsupportedOperationException.
Map<String, String> singletonMap = Collections.singletonMap("key", "value");
singletonMap.put("newKey", "newValue"); // throws UnsupportedOperationException
singletonMap.putAll(new HashMap<>()); // throws UnsupportedOperationException
singletonMap.remove("key"); // throws UnsupportedOperationException
singletonMap.replace("key", "value", "newValue"); // throws UnsupportedOperationException
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents