There have been many articles about Map in Java, which are relatively complete knowledge points. This article will not talk about these knowledge points, but from the perspective of practical use, what problems the author will consider. It is an application of knowledge.

First, before using maps, let’s consider the first question: why do we use a Map as a data structure? In my work, I often think of scenarios where Map is used:

  1. Group data according to certain rules, and use Key as group identification.
  2. Cache, with Key to do the index to find data.

Once you have confirmed that you want to use a Map, you need to decide which Map to use. The first and most common one that comes to mind is a HashMap. However, we need to pay attention to two places, whether there are requirements for thread safety and order.

Thread safety:

  1. If it isThere is no concurrent write, can be directly usedHashMap.
  2. If there isConcurrent writesIn this case, thread-safe is requiredConcurrentHashMap.

Order:

  1. Use this if you want to sort by KeyTreeMap.
  2. You can use this if you want to sort by write orderLinkedHashMap. If you want to implement LRU,LinkedHashMapIs the only choice.

If both orderliness and thread-safety are required, note that neither TreeMap nor LinkedHashMap is thread-safe. For TreeMap, can use the Collections. SynchronizedSortedMap, synchronized and lock to synchronize. Same LinkedHashMap, also can use the Collections. SynchronizedMap, synchronized, and locking to ensure the safety of the thread.

In the case where HashMap is used, WeakHashMap can be used if you intend to use it as a cache and you want the cache to be cleaned automatically.

Once you have determined the type of Map, the final consideration is whether you need to specify the initialization size.

When using HashMap, ConcurrentHashMap, and LinkedHashMap, if we know the number of stored elements in advance, we can use the following formula to calculate the initial size and pass it into the constructor to avoid unnecessary expansion.


i n i t i a l C a p a c i t y = (Number of elements / Load factor) + 1 InitialCapacity = (Number of elements/load factor) + 1

Conclusion:

  1. Whether to use Map;
  2. What type of Map to use is appropriate;
  3. Whether the initialization size can be specified.

These are some of the considerations I take into account when using Map. If there are any other considerations, please leave a comment.