Choose the Right Java Collection

Java offers you a variety of collection implementations to choose from. In general you will always look for the collection with the best performance for your programming task, which in most cases is ArrayList, HashSet or  HashMap. But be aware, if you need some special features like sorting or ordering you may need to go for a special implementation. This java collections tutorial  doesn’t include rarely used classes like WeakHashMap etc. because they are designed for very specific or exotic tasks and shouldn’t be chosen in 99% of the cases.

If you require a deep-understanding of how a specific collection is implemented you may want to read read the official Collections Framework Tutorial.

First let us look at the following flowchart. It will help you determine the collection interface to use based on the data you want to store into this collection.

java collection interfaces flowchart

The main rule here is: if you need to store values with keys mapped to them go for the Map interface, otherwise use List for values which may be duplicated and finally use the Set interface if you don’t want duplicated values in your collection.




Choose the right Java Map interface

HashMap – use this implementation if the order of items while iterating is not important to you. HashMap has better performance compared to TreeMap and LinkedHashMap

TreeMap – is ordered and sorted but slower compared to HashMap. TreeMap has ascending order of keys, according to its Comparator

LinkedHashMap – it orders items by key during insertion

Choose the right Java List interface

ArrayList – items are ordered during insertion. Search operations on ArrayLists is faster compared to search operations on LinkedLists

LinkedList – has fast adding to the start of the list, and fast deletion from the interior via iteration

Choose the right Java Set interface

HashSet – use this implementation if the order of items while iterating is not important to you. HashSet has better performance compared to TreeSet and LinkedHashSet

LinkedHashSet – it orders items during insertion

TreeSet – has ascending order of keys, according to its Comparator

 

4.2 6 votes
Article Rating
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
andrews
andrews
1 year ago

Wonderful blog which exactly matches my requirement