Many software engineers choose Java to practice for interviews, but might not be familiar with all the data structures Java offers and the differences between them. We need to learn the ins and outs of these data structures to come up with that O(log n) solution in few minutes. Since I don’t use Java in my daily work, I wanted to document a cheatsheet to remind me of all the options and help me remember what to choose on the spot when needed because let’s face it, not everyone uses a LinkedHashMap or TreeMap in their daily jobs.
Maps (Map<K, V>):
The most important Map classes you need to know are:
HashMap
LinkedHashMap
TreeMap (Red-Black Tree)
All Map classes share the following features:
Key are unique
Values can be duplicates
Null key is allowed (1 Null key since they’re unique), and values can be Null as well.
The only exception being TreeMap, where we can’t have a null key.
They are NOT thread safe.
These Map classes differ in two main factors: sorting and maintaining insertion order. Here is how to choose the right Map to solve a given problem:
Do you need to maintain insertion order? LinkedHashMap is the answer.
Do you need to have the map sorted at all times? TreeMap is the answer.
If don’t care about either of the above cases, then choose HashMap.
Another very important factor to keep in mind is the time and space these different Maps have. Let’s compare them:
Sets (Set<V>):
The most important Map classes you need to know are:
HashSet
LinkedHashSet
TreeSet (Red-Black Tree)
All Map classes share the following features:
Values are unique
Null values are allowed. The only exception being TreeSet, where we can’t have a null key.
They are NOT thread safe.
These Set classes differ in two main factors: sorting and maintaining insertion order. Here is how to choose the right Map to solve a given problem:
Do you need to maintain insertion order? LinkedHashSet is the answer.
Do you need to have the map sorted at all times? TreeSet is the answer.
If don’t care about either of the above cases, then choose HashSet.