Real-World Examples: Collection Default Methods
You'll learn: How Java's Collection interfaces use default methods to add powerful, convenient operations without breaking existing code.
The Problem They Solved
Before Java 8, the Collections Framework couldn't add new methods to core interfaces like List, Set, or Map without breaking every existing implementation. Default methods solved this by letting the JDK add useful operations directly to interfaces with ready-to-use implementations.
Key Default Methods in Collections
forEach
Instead of writing loops manually, you can iterate with an action:
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// Using default method from Iterable interface
names.forEach(name -> System.out.println(name));
removeIf
Conditionally remove elements without manual iteration complexity:
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(15);
numbers.add(20);
// Remove all even numbers - default method from Collection
numbers.removeIf(num -> num % 2 == 0);
// numbers now contains only [15]
replaceAll
Transform every element in place:
List<String> words = new ArrayList<>();
words.add("hello");
words.add("world");
// Convert all to uppercase - default method from List
words.replaceAll(word -> word.toUpperCase());
// words now contains ["HELLO", "WORLD"]
Why This Matters
These default methods were added to interfaces millions of programmers already implemented. Without default methods, every custom List or Set would have broken when Java 8 launched. Instead, they inherited working implementations automatically while maintaining the freedom to override them if needed.
Key Takeaway: Collection default methods like forEach, removeIf, and replaceAll demonstrate how default methods enable interface evolution—adding powerful functionality to core Java APIs without breaking backward compatibility.