Java_Collections_Guide
Java_Collections_Guide
Java provides a Collection Framework that includes several classes and interfaces to manage collections of objects.
These collections allow you to:
Store data.
Add and remove elements.
Find elements.
Sort elements.
And much more!
List: A collection that stores elements in a specific order. You can access elements by their position (index) in the list.
Example: A shopping list where the order matters (first item, second item, etc.).
Key classes:
ArrayList: A dynamic array that grows and shrinks.
LinkedList: A list where elements are linked together (better for adding/removing in the middle).
Example:
List<String> shoppingList = new ArrayList<>();
shoppingList.add("Milk");
shoppingList.add("Eggs");
shoppingList.add("Bread");
Set: A collection that does not allow duplicates. It does not care about the order of elements.
Key classes:
HashSet: Does not maintain any specific order.
LinkedHashSet: Maintains the order of insertion (the order in which elements were added).
TreeSet: Stores elements in sorted order.
Example:
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("John");
uniqueNames.add("Alice");
uniqueNames.add("John"); // Duplicate, will not be added
Map: A collection of key-value pairs, where each key is unique and maps to exactly one value.
Key classes:
HashMap: Stores key-value pairs with no specific order.
LinkedHashMap: Maintains insertion order of the key-value pairs.
TreeMap: Stores key-value pairs in sorted order based on keys.
Example:
Map<String, String> dictionary = new HashMap<>();
dictionary.put("Apple", "A fruit");
dictionary.put("Banana", "Another fruit");
Queue: A collection that stores elements in a First-In-First-Out (FIFO) order, like a queue at a ticket counter.
Key classes:
LinkedList: Can be used as a queue.
PriorityQueue: Orders elements based on priority, not the order they were added.
Example:
Queue<String> queue = new LinkedList<>();
queue.add("Alice");
queue.add("Bob");
queue.poll(); // Removes the first element (Alice)
Efficiency: Collections help you store and access data more efficiently. For example, HashSet allows quick lookups,
and ArrayList allows fast access by index.
Flexibility: Java provides different types of collections (list, set, map, queue) for different needs. For example, use a
Set when you don't want duplicates, or a Map when you need key-value pairs.
import java.util.*;
// Queue (FIFO)
Queue<String> queue = new LinkedList<>();
queue.add("John");
queue.add("Alice");
System.out.println("Queue (Before poll): " + queue);
queue.poll(); // Removes the first element
System.out.println("Queue (After poll): " + queue);
}
}
Output:
Conclusion:
Collections in Java are simply groups of objects. Depending on your needs (ordering, duplicates, key-value pairs),
you choose different types of collections like List, Set, Map, and Queue.
They help manage data more efficiently, whether you're storing items, ensuring uniqueness, or associating keys with
values.