If you're learning Java, you've probably heard about Collections. They are one of the most important concepts in Java because they help us store and manage multiple objects easily.
In this blog, let's understand Java Collections in a simple way.
** What is Java Collection?**
The Java Collections Framework (JCF) is a set of classes and interfaces that helps us store and manipulate groups of objects.
Instead of using arrays with a fixed size, collections can grow or shrink dynamically.
** Why Use Collections?**
- Store multiple objects
- Dynamic size
- Easy to add and remove data
- Built-in methods for searching and sorting
- Reduces coding effort
** Collection Hierarchy**
Collection
│
├── List
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector
│
├── Set
│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet
│
└── Queue
└── PriorityQueue
Map (Separate Interface)
├── HashMap
├── LinkedHashMap
└── TreeMap
Note:
Mapis not part of theCollectioninterface.
** 1. List**
A List stores elements in order and allows duplicate values.
** Example**
java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("Java");
System.out.println(list);
}
}
**Output**
[Java, Python, Java]
** 2. Set**
A Set stores only unique elements.
java
HashSet set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java");
System.out.println(set);
**Output**
[Java, Python]
** 3. Queue**
A Queue follows the FIFO (First In, First Out) rule.
java
PriorityQueue queue = new PriorityQueue<>();
queue.add(30);
queue.add(10);
queue.add(20);
System.out.println(queue.poll());
**Output**
10
** 4. Map**
A **Map** stores data as **key-value pairs**.
``java
HashMap map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
System.out.println(map);
`
`
** Common Collection Classes**
| Class | Description |
|---|---|
| ArrayList | Dynamic array |
| LinkedList | Fast insertion and deletion |
| HashSet | Stores unique elements |
| TreeSet | Stores unique elements in sorted order |
| HashMap | Stores key-value pairs |
| TreeMap | Stores sorted key-value pairs |
** Quick Comparison**
| Collection | Allows Duplicates | Maintains Order |
|---|---|---|
| List | ✅ Yes | ✅ Yes |
| Set | ❌ No | Depends on implementation |
| Queue | ✅ Yes | FIFO |
| Map | Keys ❌, Values ✅ | Depends on implementation |
** Conclusion**
The Java Collections Framework makes it easy to work with groups of objects. Remember these four main interfaces:
- List → Ordered and allows duplicates.
- Set → Stores unique elements.
- Queue → Follows FIFO.
- Map → Stores key-value pairs.
Once you understand these basics, learning advanced Java becomes much easier.

Top comments (0)