Maps in Java are the core building blocks of the Collections framework. The following tutorials will teach us the basics of working with different maps in Java.
1. Basics
- Intro to Java HashMap
- How HashMap works in Java?
- How to clone HashMap – Shallow and Deep Copy
- How to Synchronize HashMap
- How to Join or Merge Two Maps
- How to Compare Two HashMaps
- Get SubMap From Map
- Creating Nested Maps
- Creating Immutable and Unmodifiable Maps
2. Difference Between
3. Map Classes
- Java IdentityHashMap
- Java ConcurrentMap
- Java WeakHashMap
- Java TreeMap
- Java LinkedHashMap
- Java EnumMap
4. Advance Topics
- Designing a Good Custom Key for HashMap
- Performance Comparison of Different Ways to Iterate over HashMap
- Creating a Java Map with Case-Insensitive Keys
- Inverting a Map
- Convert Object to Map
- Convert a Map to Array, List or Set
5. Performance
The following table shows the relative performance of the different implementations of Map interface. Note that the final choice of Map class has to be influenced more by the functional requirements of the application and the concurrency properties. For example,
- HashMap is preferred for simple usecases with few entries.
EnumMap
should always (and only) be used for mapping from enums.- For a sorted map, use
TreeMap
where thread safety is not required,ConcurrentSkipListMap
otherwise.
Map Class | get | containsKey | next |
---|---|---|---|
HashMap | O(1) | O(1) | O(h/n) |
LinkedHashMap | O(1) | O(1) | O(1) |
IdentityHashMap | O(1) | O(1) | O(h/n) |
EnumMap | O(1) | O(1) | O(1) |
TreeMap | O(log n) | O(log n) | O(log n) |
ConcurrentHashMap | O(1) | O(1) | O(h/n) |
ConcurrentSkipListMap | O(log n) | O(log n) | O(1) |
Happy Learning !!