Which is faster in accessing elements from Java collections

collections, java, performance

Solution

Every collection type is suitable for a particular scenario. There is no fastest or best collection.

- If you need fast access to elements using index, `ArrayList` is your answer.

- If you need fast access to elements using a key, use `HashMap`.

- If you need fast add and removal of elements, use `LinkedList` (but it has a very poor index access performance).

and so on.

Problem

I am trying to understand which is faster in accessing elements from collections in Java like ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap etc. From this question: Suitable java collection for fast get and fast removal, I got to know that ArrayList takes O(1) and TreeMap as O(log n) where as this: Map/ArrayList: which one is faster to search for an element shows that ArryList is O(n), HashMap as O(1) and TreeMap as O(log n) where as this: Why is it faster to process a sorted array than an unsorted array? says that sorted array is faster than unsorted array. As the elements in TreeMap are sorted then can I assume all sorted collections are faster than un-sorted collections? Please help me in understanding which is faster to use in accessing elements from java collections of list, set, map etc implementations.

Original source

Related problems