The Java Collections Framework primarily consists of two root interfaces: Collection and Map. Since Collection extends Iterable, we can consider the framework as being built upon Iterable and Map. The Collection interface defines the contract for single-column collections that store individual elements, while the Map interface defines the contract for key-value pair collections.
- Iterable Interface: Provides iteration capabilities
- Collection Interface: Allows duplicate elements
- Set: Unordered, unique elements, accessed by element value
- List: Ordered, allows duplicates, accessed by index
- Queue: FIFO structure, allows duplicates
- Collection Interface: Allows duplicate elements
- Map Interface: Stores key-value pairs, keys must be unique
The Iterable Interface
The Iterable interface sits at the top of the collection hierarchy. Implementing this interface allows an object to be the target of a for-each loop statement.
Core Methods
// Returns an iterator over elements of type T
Iterator<T> iterator();
// Performs the given action for each element (JDK 8+)
default void forEach(Consumer<? super T> action) {}
// Creates a Spliterator for parallel traversal (JDK 8+)
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
The default keyword, introduced in Java 8, allows interfaces to provide method implementations without forcing subclasses to override them.
Using the iterator() Method
public static void demonstrateIterator() {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
The enhanced for-loop is syntactic sugar that compiles to iterator-based code:
for (String name : names) {
System.out.println(name);
}
Attempting to modify a collection while iterating through it triggers a ConcurrentModificationException due to the fail-fast mechanism:
public static void demonstrateFailFast() {
List<String> items = new ArrayList<>();
items.add("One");
items.add("Two");
items.add("Three");
for (String item : items) {
if (item.equals("One")) {
items.remove(item); // Throws ConcurrentModificationException
}
}
}
The forEach() Method
This method accepts a Consumer functional interface to process each element:
names.forEach(n -> System.out.print(n + " "));
Custom consumer implementation:
public class CustomConsumer implements Consumer<Object> {
@Override
public void accept(Object item) {
System.out.println("Processing: " + item);
}
}
// Usage
CustomConsumer consumer = new CustomConsumer();
names.forEach(consumer);
The spliterator() Method
Designed for parallel traversal, Spliterator enables efficient data partitioning for multi-core processing:
public static void demonstrateSpliterator() {
List<String> data = Arrays.asList(
"A", "B", "C", "D", "E", "F", "G", "H"
);
Spliterator<String> splitter1 = data.spliterator();
Spliterator<String> splitter2 = splitter1.trySplit();
System.out.println("First partition:");
splitter1.forEachRemaining(System.out::print);
System.out.println("\nSecond partition:");
splitter2.forEachRemaining(System.out::print);
}
Key methods include:
tryAdvance()- Processes elements one at a timeforEachRemaining()- Processes remaining elements sequentiallytrySplit()- Splits into two partitions for parallel processing
The Collection Interface
The Collection interface defines fundamental operations for single-column collections:
boolean add(E e);
boolean remove(Object o);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
void clear();
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
default boolean removeIf(Predicate<? super E> filter) {}
default Stream<E> stream() {}
default Stream<E> parallelStream() {}
Using parallel streams for concurrent processing:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
numbers.parallelStream().forEach(System.out::println);
List Interface
Lists maintain insertion order and allow index-based access:
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
ListIterator<E> listIterator();
Key implementations:
- ArrayList: Array-based, fast random access, slow insertions/deletions, not thread-safe
- LinkedList: Doubly-linked list, fast insertions/deletions, slow random access, not thread-safe
- Vector: Synchronized version of ArrayList, thread-safe
Set Interface
Sets prohibit duplicate elements:
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
boolean add(E e);
boolean remove(Object o);
Key implementations:
- HashSet: Hash table-based, unordered, allows null
- LinkedHashSet: Maintains insertion order
- TreeSet: Red-black tree implementation, sorted order
Queue Interface
Queues follow FIFO (First-In-First-Out) semantics:
boolean add(E e); // Throws exception on failure
boolean offer(E e); // Returns false on failure
E remove(); // Throws exception if empty
E poll(); // Returns null if empty
E element(); // Throws exception if empty
E peek(); // Returns null if empty
Key implementations:
- ArrayDeque: Resizable array implementation of Deque
- PriorityQueue: Heap-based, orders elements by priority
- BlockingQueue: Supports concurrent blocking operations
The Map Interface
Maps store key-value pairs with unique keys:
V put(K key, V value);
V remove(Object key);
V get(Object key);
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
default V getOrDefault(Object key, V defaultValue) {}
default V putIfAbsent(K key, V value) {}
default void forEach(BiConsumer<? super K, ? super V> action) {}
Key implementations:
- HashMap: Hash table-based, unordered, not thread-safe
- LinkedHashMap: Maintains insertion or access order
- ConcurrentHashMap: Thread-safe, optimized for concurrent access
- Hashtable: Legacy synchronized implementation
The Map.Entry<K,V> interface represents a single key-value pair within a Map.