Java Collections Framework - Interactive Examples

Java Collections Framework Overview

The Java Collections Framework provides a unified architecture for storing and manipulating groups of objects. It includes interfaces, implementations, and algorithms.

Core Interfaces

  • Collection: Root interface
  • List: Ordered collection
  • Set: No duplicates
  • Map: Key-value pairs
  • Queue: FIFO order

Key Benefits

  • Reduces programming effort
  • Increases performance
  • Provides interoperability
  • Reduces learning curve
  • Promotes code reuse

Common Implementations

  • ArrayList, LinkedList
  • HashSet, TreeSet
  • HashMap, TreeMap
  • PriorityQueue, ArrayDeque
  • Stack, Vector

Collections Hierarchy

// Collections Framework Hierarchy Collection ├── List │ ├── ArrayList │ ├── LinkedList │ └── Vector │ └── Stack ├── Set │ ├── HashSet │ ├── LinkedHashSet │ └── SortedSet │ └── TreeSet └── Queue ├── LinkedList ├── PriorityQueue └── Deque └── ArrayDeque Map ├── HashMap ├── LinkedHashMap ├── Hashtable └── SortedMap └── TreeMap

List Interface

List is an ordered collection that can contain duplicate elements. Elements can be accessed by their index.

ArrayList Example

import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String[] args) { // Creating an ArrayList List<String> fruits = new ArrayList<>(); // Adding elements fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add(1, "Mango"); // Insert at index 1 // Accessing elements System.out.println("First fruit: " + fruits.get(0)); System.out.println("All fruits: " + fruits); // Modifying elements fruits.set(2, "Grapes"); // Removing elements fruits.remove("Banana"); fruits.remove(0); // Remove by index // Iterating through the list for (String fruit : fruits) { System.out.println(fruit); } } }
Output: First fruit: Apple All fruits: [Apple, Mango, Banana, Orange] Grapes Orange

LinkedList Example

import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { LinkedList<Integer> numbers = new LinkedList<>(); // Adding elements numbers.add(10); numbers.addFirst(5); numbers.addLast(20); numbers.add(2, 15); System.out.println("LinkedList: " + numbers); // Accessing elements System.out.println("First: " + numbers.getFirst()); System.out.println("Last: " + numbers.getLast()); // Removing elements numbers.removeFirst(); numbers.removeLast(); // Using as a queue numbers.offer(30); // Add to end Integer polled = numbers.poll(); // Remove from beginning System.out.println("After operations: " + numbers); } }

Interactive ArrayList Demo

List Implementations Comparison

Feature ArrayList LinkedList Vector
Internal Structure Dynamic array Doubly linked list Dynamic array
Random Access O(1) O(n) O(1)
Insertion/Deletion at beginning O(n) O(1) O(n)
Thread Safe No No Yes
Memory Overhead Low High Low

Set Interface

Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction.

HashSet Example

import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String[] args) { Set<String> colors = new HashSet<>(); // Adding elements colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.add("Red"); // Duplicate - won't be added System.out.println("HashSet: " + colors); System.out.println("Size: " + colors.size()); // Checking existence if (colors.contains("Blue")) { System.out.println("Blue is in the set"); } // Set operations Set<String> moreColors = new HashSet<>(); moreColors.add("Yellow"); moreColors.add("Blue"); moreColors.add("Black"); // Union Set<String> union = new HashSet<>(colors); union.addAll(moreColors); System.out.println("Union: " + union); // Intersection Set<String> intersection = new HashSet<>(colors); intersection.retainAll(moreColors); System.out.println("Intersection: " + intersection); } }

TreeSet Example

import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); // Adding elements numbers.add(45); numbers.add(12); numbers.add(78); numbers.add(34); numbers.add(89); numbers.add(23); System.out.println("TreeSet (sorted): " + numbers); // NavigableSet operations System.out.println("First: " + numbers.first()); System.out.println("Last: " + numbers.last()); System.out.println("Lower than 50: " + numbers.lower(50)); System.out.println("Higher than 50: " + numbers.higher(50)); // Subset operations System.out.println("SubSet (20-60): " + numbers.subSet(20, 60)); } }

Interactive Set Operations Demo

Set A

Set B

Result

Map Interface

Map is an object that maps keys to values. A map cannot contain duplicate keys.

HashMap Example

import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); // Adding key-value pairs scores.put("Alice", 95); scores.put("Bob", 87); scores.put("Charlie", 92); scores.put("David", 88); // Accessing values System.out.println("Bob's score: " + scores.get("Bob")); // Updating values scores.put("Bob", 90); // Checking existence if (scores.containsKey("Eve")) { System.out.println("Eve's score: " + scores.get("Eve")); } else { scores.putIfAbsent("Eve", 85); } // Iterating through entries for (Map.Entry<String, Integer> entry : scores.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } // Using compute methods scores.compute("Alice", (k, v) -> v + 5); // Add 5 to Alice's score scores.computeIfPresent("Bob", (k, v) -> v * 2); // Double Bob's score } }

TreeMap Example

import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { TreeMap<String, String> countries = new TreeMap<>(); // Adding entries countries.put("USA", "Washington DC"); countries.put("UK", "London"); countries.put("France", "Paris"); countries.put("Germany", "Berlin"); countries.put("Japan", "Tokyo"); System.out.println("TreeMap (sorted by key): " + countries); // NavigableMap operations System.out.println("First entry: " + countries.firstEntry()); System.out.println("Last key: " + countries.lastKey()); System.out.println("Lower than 'India': " + countries.lowerKey("India")); // Submap System.out.println("Countries F-J: " + countries.subMap("F", "K")); } }

Interactive HashMap Demo

Map Implementations Comparison

Feature HashMap TreeMap LinkedHashMap
Ordering No ordering Sorted by keys Insertion order
Null keys One null key allowed No null keys One null key allowed
Performance O(1) O(log n) O(1)
Memory overhead Low High Medium

Queue Interface

Queue is a collection designed for holding elements prior to processing. Typically ordered in FIFO manner.

PriorityQueue Example

import java.util.PriorityQueue; import java.util.Comparator; public class PriorityQueueExample { public static void main(String[] args) { // Min heap (default) PriorityQueue<Integer> minHeap = new PriorityQueue<>(); minHeap.offer(50); minHeap.offer(10); minHeap.offer(30); minHeap.offer(20); minHeap.offer(40); System.out.println("Min Heap:"); while (!minHeap.isEmpty()) { System.out.print(minHeap.poll() + " "); } // Max heap PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); maxHeap.offer(50); maxHeap.offer(10); maxHeap.offer(30); maxHeap.offer(20); maxHeap.offer(40); System.out.println("\n\nMax Heap:"); while (!maxHeap.isEmpty()) { System.out.print(maxHeap.poll() + " "); } // Custom comparator example PriorityQueue<String> tasks = new PriorityQueue<>( Comparator.comparingInt(String::length) ); tasks.offer("Write report"); tasks.offer("Fix bug"); tasks.offer("Review code"); tasks.offer("Deploy"); System.out.println("\n\nTasks by length:"); while (!tasks.isEmpty()) { System.out.println(tasks.poll()); } } }

ArrayDeque Example

import java.util.ArrayDeque; import java.util.Deque; public class ArrayDequeExample { public static void main(String[] args) { Deque<String> deque = new ArrayDeque<>(); // Using as a queue (FIFO) deque.offer("First"); deque.offer("Second"); deque.offer("Third"); System.out.println("Queue operations:"); System.out.println("Poll: " + deque.poll()); System.out.println("Remaining: " + deque); // Using as a stack (LIFO) deque.clear(); deque.push("Bottom"); deque.push("Middle"); deque.push("Top"); System.out.println("\nStack operations:"); System.out.println("Pop: " + deque.pop()); System.out.println("Remaining: " + deque); // Double-ended operations deque.clear(); deque.addFirst("Front"); deque.addLast("Back"); deque.addFirst("New Front"); deque.addLast("New Back"); System.out.println("\nDeque: " + deque); System.out.println("First: " + deque.peekFirst()); System.out.println("Last: " + deque.peekLast()); } }

Interactive Queue Demo

Collections Utility Class

The Collections class provides static methods for operating on collections.

Sorting and Searching

import java.util.*; public class CollectionsUtilExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>( Arrays.asList(42, 18, 73, 56, 24, 91) ); // Sorting Collections.sort(numbers); System.out.println("Sorted: " + numbers); // Reverse sorting Collections.sort(numbers, Collections.reverseOrder()); System.out.println("Reverse sorted: " + numbers); // Binary search (list must be sorted) Collections.sort(numbers); int index = Collections.binarySearch(numbers, 56); System.out.println("Index of 56: " + index); // Shuffling Collections.shuffle(numbers); System.out.println("Shuffled: " + numbers); // Min and Max System.out.println("Min: " + Collections.min(numbers)); System.out.println("Max: " + Collections.max(numbers)); // Frequency List<String> words = Arrays.asList( "apple", "banana", "apple", "orange", "apple" ); System.out.println("Frequency of 'apple': " + Collections.frequency(words, "apple")); } }

Synchronization and Immutability

import java.util.*; public class SyncAndImmutableExample { public static void main(String[] args) { // Creating synchronized collections List<String> list = new ArrayList<>(); List<String> syncList = Collections.synchronizedList(list); Map<String, Integer> map = new HashMap<>(); Map<String, Integer> syncMap = Collections.synchronizedMap(map); // Creating unmodifiable collections List<String> fruits = Arrays.asList("Apple", "Banana", "Orange"); List<String> immutableList = Collections.unmodifiableList(fruits); // This will throw UnsupportedOperationException // immutableList.add("Grape"); // Empty collections List<String> emptyList = Collections.emptyList(); Set<Integer> emptySet = Collections.emptySet(); Map<String, Object> emptyMap = Collections.emptyMap(); // Singleton collections Set<String> singleton = Collections.singleton("OnlyOne"); System.out.println("Singleton set: " + singleton); } }

Advanced Operations

import java.util.*; public class AdvancedCollectionsExample { public static void main(String[] args) { // Rotating elements List<String> list = new ArrayList<>( Arrays.asList("A", "B", "C", "D", "E") ); Collections.rotate(list, 2); System.out.println("Rotated by 2: " + list); // Replacing elements Collections.replaceAll(list, "A", "X"); System.out.println("After replacement: " + list); // Filling List<Integer> numbers = new ArrayList<>(Collections.nCopies(5, 0)); Collections.fill(numbers, 42); System.out.println("Filled list: " + numbers); // Disjoint check List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> list3 = Arrays.asList(3, 4, 5); System.out.println("list1 and list2 disjoint: " + Collections.disjoint(list1, list2)); System.out.println("list1 and list3 disjoint: " + Collections.disjoint(list1, list3)); } }

Interactive Collections Utilities Demo

Best Practices

Choose the Right Collection

  • Use ArrayList for random access
  • Use LinkedList for frequent insertions/deletions
  • Use HashSet for unique elements
  • Use TreeSet for sorted unique elements
  • Use HashMap for key-value lookups

Performance Tips

  • Initialize collections with capacity
  • Use primitive collections for better performance
  • Consider concurrent collections for thread safety
  • Use immutable collections when possible
  • Profile your code to find bottlenecks

Common Pitfalls

  • Modifying collections during iteration
  • Not implementing equals/hashCode properly
  • Using raw types instead of generics
  • Ignoring null handling
  • Not considering thread safety

Iterators in Java Collections

Iterator is an interface in Java used to traverse through the elements of a Collection. It provides methods to iterate, remove, and check existence of elements in a collection.

Basic Iterator Example

import java.util.*; public class IteratorExample { public static void main(String[] args) { List<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Goat"); Iterator<String> iterator = animals.iterator(); // Traversing using while loop while (iterator.hasNext()) { String animal = iterator.next(); System.out.println(animal); } } }

Removing Elements Using Iterator

import java.util.*; public class IteratorRemoveExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); Iterator<Integer> iterator = numbers.iterator(); // Removing even numbers while (iterator.hasNext()) { Integer num = iterator.next(); if (num % 2 == 0) { iterator.remove(); } } System.out.println("After removal: " + numbers); } }

ListIterator Example

import java.util.*; public class ListIteratorExample { public static void main(String[] args) { List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie")); ListIterator<String> listIterator = names.listIterator(); // Forward iteration while (listIterator.hasNext()) { System.out.println("Next: " + listIterator.next()); } // Backward iteration while (listIterator.hasPrevious()) { System.out.println("Previous: " + listIterator.previous()); } } }

Spliterator Example

import java.util.*; public class SpliteratorExample { public static void main(String[] args) { List<String> items = Arrays.asList("One", "Two", "Three", "Four"); Spliterator<String> spliterator = items.spliterator(); spliterator.forEachRemaining(System.out::println); } }

Quiz: Identify the Correct Use

Q: Which of the following is true about ListIterator?

  • A. It can only iterate forward.
  • B. It does not support element removal.
  • C. It allows bidirectional traversal of lists.
  • D. It is used only with Sets.

Interactive Iterator Demo