Core Java
core19CollectionsDemo
- Path
- pkg1core/core19CollectionsDemo.java
- Package
- pkg1core
- Study order
- 20
- Run
- Single-file source launch
- Command
- java pkg1core/core19CollectionsDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core19CollectionsDemo.java5 * --------------------6 * The Collections Framework: List, Set, Map, Queue, Deque, and when to use each.7 *8 * EXPLANATION:9 * - List: ordered, indexed, allows duplicates (ArrayList / LinkedList).10 * - Set: no duplicates (HashSet=unordered, LinkedHashSet=insertion, TreeSet=sorted).11 * - Map: key->value (HashMap, LinkedHashMap, TreeMap).12 * - Queue/Deque: FIFO/LIFO (ArrayDeque), PriorityQueue=min-heap.13 */14import java.util.*;15 16public class core19CollectionsDemo {17 public static void main(String[] args) {18 // ---- List ----19 List<String> list = new ArrayList<>(List.of("b", "a", "c", "a"));20 list.add("d");21 Collections.sort(list);22 System.out.println("List (sorted, dups kept): " + list + " get(0)=" + list.get(0));23 24 // ---- Set (uniqueness) ----25 Set<String> hash = new HashSet<>(list);26 Set<String> tree = new TreeSet<>(list); // sorted, unique27 System.out.println("HashSet (unordered, unique): " + hash);28 System.out.println("TreeSet (sorted, unique): " + tree);29 30 // ---- Map ----31 Map<String, Integer> counts = new HashMap<>();32 for (String s : list) counts.merge(s, 1, Integer::sum); // frequency count idiom33 System.out.println("Frequency map: " + counts);34 System.out.println("getOrDefault('z',0): " + counts.getOrDefault("z", 0));35 counts.computeIfAbsent("e", k -> 0);36 System.out.println("after computeIfAbsent: " + counts);37 38 // TreeMap keeps keys sorted39 TreeMap<String, Integer> sortedMap = new TreeMap<>(counts);40 System.out.println("TreeMap firstKey=" + sortedMap.firstKey() + " lastKey=" + sortedMap.lastKey());41 42 // ---- Queue (FIFO) ----43 Queue<Integer> q = new ArrayDeque<>();44 q.offer(1); q.offer(2); q.offer(3);45 System.out.println("Queue poll order: " + q.poll() + ", " + q.poll());46 47 // ---- Deque as Stack (LIFO) ----48 Deque<Integer> stack = new ArrayDeque<>();49 stack.push(1); stack.push(2); stack.push(3);50 System.out.println("Stack pop order: " + stack.pop() + ", " + stack.pop());51 52 // ---- PriorityQueue (min-heap) ----53 PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 3, 2, 4));54 StringBuilder order = new StringBuilder();55 while (!pq.isEmpty()) order.append(pq.poll()).append(' ');56 System.out.println("PriorityQueue ascending: " + order.toString().trim());57 58 // Iteration safety: remove while iterating via Iterator59 List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));60 Iterator<Integer> it = nums.iterator();61 while (it.hasNext()) if (it.next() % 2 == 0) it.remove();62 System.out.println("After removing evens: " + nums);63 }64}