![]() ![]() Static Initializer – For static Map variable.Create a function to return a Map – It works everywhere.Java 9 Map.ofEntries – Same as the above.Java 9 Map.of – If you have Java 9 and want to create an immutable Map.Collections.singletonMap – Less use cases.Initialize a HashMap (Standard) – The best.Map.put("key4", "value4") // no problem.īelow is a little review of each of the ways to initialize a HashMap. New AbstractMap.SimpleEntry("ke圓", "value3")) New AbstractMap.SimpleEntry("key2", "value2"), New AbstractMap.SimpleEntry("key1", "value1"), This example creates a stream of SimpleEntry and returns a mutable map.ĭo not use the below method to initialize a HashMap, I don’t see any benefits of a stream of SimpleEntry, error-prone and ugly syntax, just for reference. This solution is for a static Map variable, and it returns a mutable map. Map.put("key4", "value4") // yes, we can do it It works for all Java versions, mutable map. We can create a function to initialize a HashMap, which works for all Java versions. Map.put("key4", "value4") // throws UnsupportedOperationException Java 9, no limit of Map entry, immutable map. Java 9 introduced a similar API, Map.ofEntries, which returns an unmodifiable or immutable map, but this Map has no limit of the Map entry, and we can create as many entries as we want. ImmutableMap.put("key4", "value4") // UnsupportedOperationException (immutableMap.getClass()) // $UnmodifiableMap Map immutableMap = Collections.unmodifiableMap(map) The result is a mutable map, and we can use Collections.unmodifiableMap to convert a mutable map to an immutable map. This example is a standard Java way to declare and initialize a HashMap. Immutable map – It means we can’t add or modify the Map entries, and if we modify it, it throws UnsupportedOperationException. ![]() Mutable map – It means we can modify the Map entries.This article shows different ways to initialize HashMap in Java.Īfter initialized a HashMap, the result is either a mutable map or an immutable map: Tags: java 9 | java basic | java collections | map ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |