The collection in Java is a framework that provides an architecture to store and manipulate the group of objects. A collection represents a single unit of objects.
Java collections are:
1. Lists
2. Sets
3. Maps
4. Queue
The guidelines for choosing the right Java Collection are based on what your application demands. The general guidelines for choosing the right Java collection is
1. Lists:
I. ArrayList: Items are ordered during insertions. Search operations on ArrayList are faster compared to search operations on LinkedList.
II. Linked List: Adding and removing is fast
Uses:
Can be used to store and iterate through a bunch of things.
2. Sets:
I. HashSet: If the iteration does not have to be in order, implementing HashSet can be useful. It has a better performance compared to TreeSet and LinkedSet.
II. LinkedHashSet: It maintains insertion order; it permits null elements.
III. TreeSet: It does not allow null elements, access and retrieval times are fast, and it maintains ascending order.
Uses:
Typically it is used to remember which items have already been processed.
3. Map:
I. HashMap: This can be implemented if the order of items while iteration is not important. It has a better performance compared to TreeMap and LinkedHashMap.
II. TreeMap: It is ordered and sorted but is slower, it has ascending order of keys.
III. LinkedHashMap: It orders items by key during insertion.
Uses:
A map cannot contain duplicate keys and each key can map to at most one value. It can be used to perform lookups by keys and to retrieve and update elements by keys. It is perfect for key-value association mapping such as dictionaries. It is often useful for implementing in-memory caches or indexes.
4. Queue: It maintains the FIFO (First-in-first-out) order. It can be an ordered list that is used to hold the elements which are about to be processed. It is an ordered list of objects with its use limited to inserting elements at the end of the list and deleting elements from the start of the list.
I. PriorityQueue: It implements the queue interface. It holds the elements or objects which are to be processed by their priorities. It doesn’t allow null values to be stored.
II. Deque Interface: It extends the Queue interface. It can be useful if we want to add or remove elements from both ends. It stands for the double-ended queue (Deque).