Java Collections Framework
1. List
List is an ordered collection that allows duplicate elements. You can access elements using an index.
ArrayList Example
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // Apple
LinkedList Example
List<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.remove(0); // removes "A"
Stack Example
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // 2
2. Set
Set does not allow duplicate elements and is mostly used when uniqueness is required.
HashSet Example
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Java"); // Ignored
LinkedHashSet Example
Set<String> set = new LinkedHashSet<>();
set.add("A");
set.add("B");
TreeSet Example
Set<Integer> set = new TreeSet<>();
set.add(10);
set.add(5);
System.out.println(set); // [5, 10]
3. Queue
Queue stores elements in First-In-First-Out (FIFO) order. It is commonly used in scheduling or task queues.
PriorityQueue Example
Queue<Integer> queue = new PriorityQueue<>();
queue.add(20);
queue.add(10);
System.out.println(queue.poll()); // 10
4. Deque
Deque (Double-Ended Queue) allows inserting and removing elements from both front and rear.
ArrayDeque Example
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("A");
deque.addLast("B");
System.out.println(deque.removeFirst()); // A
5. Map
Map stores key-value pairs. Keys must be unique, but values can be duplicated.
HashMap Example
Map<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(1, "C"); // Replaces "A"
LinkedHashMap Example
Map<String, String> map = new LinkedHashMap<>();
map.put("A", "Apple");
map.put("B", "Banana");
TreeMap Example
Map<Integer, String> map = new TreeMap<>();
map.put(2, "B");
map.put(1, "A");
System.out.println(map); // Sorted by key
Collection Type Summary
| Collection Type | Ordered | Allows Duplicates | Sorted | Examples |
|---|---|---|---|---|
| List | Yes | Yes | No | ArrayList, LinkedList |
| Set | No | No | TreeSet only | HashSet, TreeSet |
| Queue | Yes | Yes | PriorityQueue | LinkedList, PriorityQueue |
| Map | No | Keys: No, Values: Yes | TreeMap only | HashMap, TreeMap |