๐ Introduction
As your Java application grows, handling large sets of data becomes common. The Collections Framework provides powerful classes to store, manipulate, and organize groups of objects.
In this lesson, weโll explore the three most commonly used interfaces:
List
Set
Map
๐งบ What is the Collections Framework?
The Collections Framework is a set of interfaces and classes in java.util
that help you work with groups of objects more easily.
๐ 1. List โ Ordered & Duplicates Allowed
A List
is an ordered collection that allows duplicates.
โ Common Implementations:
ArrayList
(most used)LinkedList
๐น Example:
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // duplicate allowed
System.out.println(names); // [Alice, Bob, Alice]
}
}
๐ข 2. Set โ Unordered & No Duplicates
A Set
is a collection that does not allow duplicates.
โ Common Implementations:
HashSet
(unordered)LinkedHashSet
(keeps insertion order)TreeSet
(sorted)
๐น Example:
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // duplicate ignored
System.out.println(fruits); // [Apple, Banana]
}
}
๐ 3. Map โ Key-Value Pairs
A Map
stores key-value pairs, like a dictionary.
โ Common Implementations:
HashMap
(unordered)LinkedHashMap
(insertion order)TreeMap
(sorted keys)
๐น Example:
import java.util.*;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Alice", 95); // overwrites previous value
System.out.println(scores); // {Alice=95, Bob=85}
}
}
๐ง Useful Methods:
scores.get("Alice");
scores.containsKey("Bob");
scores.remove("Alice");
scores.keySet(); // returns all keys
scores.values(); // returns all values
๐ง When to Use What?
Collection | Allows Duplicates | Maintains Order | Key-Value Storage |
---|---|---|---|
List | โ | โ | โ |
Set | โ | โ (except LinkedHashSet ) | โ |
Map | โ (keys must be unique) | N/A | โ
|
๐งช Mini Challenge
List<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
nums.add(10);
Set<Integer> uniqueNums = new HashSet<>(nums);
System.out.println("Unique: " + uniqueNums);
โ What You Learned
- The core Java collections:
List
,Set
, andMap
- How to choose the right one based on your needs
- Real-world examples and key operations